├── tradesv3.dryrun.sqlite ├── TensorBoardScreenshot.png ├── rllib_example.py ├── deep_rl.py ├── neat_config ├── config_rl.json ├── .gitignore ├── README.md ├── neat_trade.py ├── freqtradegym.py ├── LoadRLModel.py ├── IndicatorforRL.py ├── Neat_RL.py └── LICENSE /tradesv3.dryrun.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugocen/freqtrade-gym/HEAD/tradesv3.dryrun.sqlite -------------------------------------------------------------------------------- /TensorBoardScreenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugocen/freqtrade-gym/HEAD/TensorBoardScreenshot.png -------------------------------------------------------------------------------- /rllib_example.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from freqtrade.configuration import Configuration 3 | 4 | config = Configuration.from_files(['config_rl.json']) 5 | 6 | from freqtradegym import TradingEnv 7 | 8 | import ray 9 | from ray.tune.registry import register_env 10 | from ray.rllib.agents import ppo 11 | 12 | def env_creator(env_config): 13 | return TradingEnv(config) # return an env instance 14 | 15 | 16 | 17 | if __name__ == "__main__": 18 | # env = TradingEnv(config) 19 | ray.init() 20 | register_env("my_env", env_creator) 21 | trainer = ppo.PPOTrainer(env="my_env") 22 | 23 | while True: 24 | print(trainer.train()) -------------------------------------------------------------------------------- /deep_rl.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from freqtrade.configuration import Configuration 3 | 4 | config = Configuration.from_files(['config_rl.json']) 5 | 6 | 7 | from freqtradegym import TradingEnv 8 | from stable_baselines.common.policies import MlpPolicy 9 | 10 | from stable_baselines import ACER 11 | 12 | if __name__ == "__main__": 13 | 14 | env = TradingEnv(config) 15 | policy_kwargs = dict(layers=[32, 32]) 16 | model = ACER( 17 | MlpPolicy, env, 18 | learning_rate=1e-4, 19 | policy_kwargs=policy_kwargs, 20 | verbose=0, 21 | tensorboard_log="./tensorboard/") 22 | 23 | model.learn(total_timesteps=int(1e+6)) 24 | model.save('model') 25 | -------------------------------------------------------------------------------- /neat_config: -------------------------------------------------------------------------------- 1 | [NEAT] 2 | fitness_criterion = max 3 | fitness_threshold = 0.5 4 | pop_size = 500 5 | reset_on_extinction = False 6 | no_fitness_termination = True 7 | 8 | [DefaultGenome] 9 | # node activation options 10 | activation_default = tanh 11 | activation_mutate_rate = 0.2 12 | activation_options = clamped relu sigmoid tanh 13 | 14 | # node aggregation options 15 | aggregation_default = sum 16 | aggregation_mutate_rate = 0.0 17 | aggregation_options = sum 18 | 19 | # node bias options 20 | bias_init_mean = 0.0 21 | bias_init_stdev = 1.0 22 | bias_max_value = 30.0 23 | bias_min_value = -30.0 24 | bias_mutate_power = 0.5 25 | bias_mutate_rate = 0.7 26 | bias_replace_rate = 0.1 27 | 28 | # genome compatibility options 29 | compatibility_disjoint_coefficient = 1.0 30 | compatibility_weight_coefficient = 0.5 31 | 32 | # connection add/remove rates 33 | conn_add_prob = 0.5 34 | conn_delete_prob = 0.5 35 | 36 | # connection enable options 37 | enabled_default = True 38 | enabled_mutate_rate = 0.01 39 | 40 | feed_forward = True 41 | initial_connection = full 42 | 43 | # node add/remove rates 44 | node_add_prob = 0.5 45 | node_delete_prob = 0.2 46 | 47 | # network parameters 48 | num_hidden = 0 49 | num_inputs = 55 50 | num_outputs = 3 51 | 52 | # node response options 53 | response_init_mean = 1.0 54 | response_init_stdev = 0.0 55 | response_max_value = 30.0 56 | response_min_value = -30.0 57 | response_mutate_power = 0.0 58 | response_mutate_rate = 0.0 59 | response_replace_rate = 0.0 60 | 61 | # connection weight options 62 | weight_init_mean = 0.0 63 | weight_init_stdev = 1.0 64 | weight_max_value = 30 65 | weight_min_value = -30 66 | weight_mutate_power = 0.5 67 | weight_mutate_rate = 0.8 68 | weight_replace_rate = 0.1 69 | 70 | [DefaultSpeciesSet] 71 | compatibility_threshold = 5.0 72 | 73 | [DefaultStagnation] 74 | species_fitness_func = max 75 | max_stagnation = 15 76 | species_elitism = 2 77 | 78 | [DefaultReproduction] 79 | elitism = 2 80 | survival_threshold = 0.2 -------------------------------------------------------------------------------- /config_rl.json: -------------------------------------------------------------------------------- 1 | { 2 | "gym_parameters": { 3 | "indicator_strategy": "IndicatorforRL", 4 | "fee": 0.0015, 5 | "timerange": "20201120-20201130", 6 | "simulate_length": 200 7 | }, 8 | "max_open_trades": 3, 9 | "stake_currency": "USDT", 10 | "stake_amount": 50, 11 | "tradable_balance_ratio": 0.99, 12 | "fiat_display_currency": "TWD", 13 | "ticker_interval": "15m", 14 | "dry_run": true, 15 | "dry_run_wallet": 400, 16 | "unfilledtimeout": { 17 | "buy": 10, 18 | "sell": 30 19 | }, 20 | "fee": 0.0015, 21 | "bid_strategy": { 22 | "ask_last_balance": 0.0, 23 | "use_order_book": false, 24 | "order_book_top": 1, 25 | "check_depth_of_market": { 26 | "enabled": false, 27 | "bids_to_ask_delta": 1 28 | } 29 | }, 30 | "ask_strategy": { 31 | "use_order_book": false, 32 | "order_book_min": 1, 33 | "order_book_max": 9, 34 | "use_sell_signal": true, 35 | "sell_profit_only": false, 36 | "ignore_roi_if_buy_signal": false 37 | }, 38 | "exchange": { 39 | "name": "binance", 40 | "key": "", 41 | "secret": "", 42 | "ccxt_config": {"enableRateLimit": true}, 43 | "ccxt_async_config": { 44 | "enableRateLimit": true 45 | }, 46 | "pair_whitelist": [ 47 | "BTC/USDT" 48 | ], 49 | "pair_blacklist": [ 50 | "BNB/USDT", 51 | "BSDC/USDT", 52 | "USDC/USDT", 53 | "TUSD/USDT", 54 | "PAX/USDT" 55 | ] 56 | }, 57 | "pairlists": [ 58 | {"method": "StaticPairList"} 59 | ], 60 | "edge": { 61 | "enabled": false, 62 | "process_throttle_secs": 3600, 63 | "calculate_since_number_of_days": 7, 64 | "allowed_risk": 0.01, 65 | "stoploss_range_min": -0.01, 66 | "stoploss_range_max": -0.1, 67 | "stoploss_range_step": -0.01, 68 | "minimum_winrate": 0.60, 69 | "minimum_expectancy": 0.20, 70 | "min_trade_number": 10, 71 | "max_trade_duration_minute": 1440, 72 | "remove_pumps": false 73 | }, 74 | "telegram": { 75 | "enabled": false, 76 | "token": "", 77 | "chat_id": "" 78 | }, 79 | "initial_state": "running", 80 | "forcebuy_enable": false, 81 | "internals": { 82 | "process_throttle_secs": 5 83 | } 84 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | user_data/ 2 | tensorboard/ 3 | .vscode/ 4 | *.zip 5 | 6 | # Byte-compiled / optimized / DLL files 7 | __pycache__/ 8 | *.py[cod] 9 | *$py.class 10 | 11 | # C extensions 12 | *.so 13 | 14 | # Distribution / packaging 15 | .Python 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | lib/ 23 | lib64/ 24 | parts/ 25 | sdist/ 26 | var/ 27 | wheels/ 28 | pip-wheel-metadata/ 29 | share/python-wheels/ 30 | *.egg-info/ 31 | .installed.cfg 32 | *.egg 33 | MANIFEST 34 | 35 | # PyInstaller 36 | # Usually these files are written by a python script from a template 37 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 38 | *.manifest 39 | *.spec 40 | 41 | # Installer logs 42 | pip-log.txt 43 | pip-delete-this-directory.txt 44 | 45 | # Unit test / coverage reports 46 | htmlcov/ 47 | .tox/ 48 | .nox/ 49 | .coverage 50 | .coverage.* 51 | .cache 52 | nosetests.xml 53 | coverage.xml 54 | *.cover 55 | *.py,cover 56 | .hypothesis/ 57 | .pytest_cache/ 58 | 59 | # Translations 60 | *.mo 61 | *.pot 62 | 63 | # Django stuff: 64 | *.log 65 | local_settings.py 66 | db.sqlite3 67 | db.sqlite3-journal 68 | 69 | # Flask stuff: 70 | instance/ 71 | .webassets-cache 72 | 73 | # Scrapy stuff: 74 | .scrapy 75 | 76 | # Sphinx documentation 77 | docs/_build/ 78 | 79 | # PyBuilder 80 | target/ 81 | 82 | # Jupyter Notebook 83 | .ipynb_checkpoints 84 | 85 | # IPython 86 | profile_default/ 87 | ipython_config.py 88 | 89 | # pyenv 90 | .python-version 91 | 92 | # pipenv 93 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 94 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 95 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 96 | # install all needed dependencies. 97 | #Pipfile.lock 98 | 99 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 100 | __pypackages__/ 101 | 102 | # Celery stuff 103 | celerybeat-schedule 104 | celerybeat.pid 105 | 106 | # SageMath parsed files 107 | *.sage.py 108 | 109 | # Environments 110 | .env 111 | .venv 112 | env/ 113 | venv/ 114 | ENV/ 115 | env.bak/ 116 | venv.bak/ 117 | 118 | # Spyder project settings 119 | .spyderproject 120 | .spyproject 121 | 122 | # Rope project settings 123 | .ropeproject 124 | 125 | # mkdocs documentation 126 | /site 127 | 128 | # mypy 129 | .mypy_cache/ 130 | .dmypy.json 131 | dmypy.json 132 | 133 | # Pyre type checker 134 | .pyre/ 135 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # freqtrade-gym 2 | 3 | This project is base on [freqtrade](https://github.com/freqtrade/freqtrade) 4 | 5 | The project is in very early stage, so there are a lot of inconvenient part that you have to set up manually. I am working on the improvements. 6 | 7 | ## Installation 8 | ### 1. freqtrade 9 | Follow the [freqtrade documentation](https://www.freqtrade.io/en/latest/) to install freqtrade 10 | 11 | Initialize the user_directory 12 | ```sh 13 | freqtrade create-userdir --userdir user_data/ 14 | ``` 15 | 16 | ### 2. Pandas 17 | ```sh 18 | pip install pandas 19 | ``` 20 | 21 | ### 3. OpenAI Gym 22 | ```sh 23 | pip install gym 24 | ``` 25 | 26 | ### 4. Copy freqtrade-gym files 27 | #### Baseline files 28 | IndicatorforRL.py -> [freqtrade home]/user_data/strategies/IndicatorforRL.py 29 | config_rl.json -> [freqtrade home]/config_rl.json 30 | freqtradegym.py -> [freqtrade home]/freqtradegym.py 31 | deep_rl.py -> [freqtrade home]/deep_rl.py 32 | #### RLib 33 | Copy first the baseline files. 34 | LoadRLModel.py -> [freqtrade home]/user_data/strategies/LoadRLModel.py 35 | rllib_example.py -> [freqtrade home]/rllib_example.py 36 | 37 | ## Example Usage (baseline) 38 | The usage example is deep_rl.py and the config for freqtrade and freqtrade-gym is config_rl.json and uses IndicatorforRL.py as feature extraction. 39 | This demo is using [openai baseline library](https://github.com/hill-a/stable-baselines) to train reinforcement learning agents. 40 | Baseline can install by 41 | ```sh 42 | sudo apt-get update && sudo apt-get install cmake libopenmpi-dev python3-dev zlib1g-dev 43 | pip install stable-baselines[mpi] 44 | ``` 45 | 46 | Download historical data 47 | (Remember to download a little bit more data than the timerange in config file just in case.) 48 | ```sh 49 | freqtrade download-data -c --days -t {1m,3m,5m...} 50 | ``` 51 | To match the example config_rl.json 52 | ```sh 53 | freqtrade download-data -c config_rl.json --timerange 20201119-20201201 -t 15m 54 | ``` 55 | 56 | Move the IndicatorforRL.py into user_data/strategies (you should have user_data/strategies/IndicatorforRL.py) 57 | 58 | Run the demo to train an agent. 59 | ```sh 60 | python deep_rl.py 61 | ``` 62 | 63 | You can use tensorboard to monior the training process 64 | logdir is defined in deep_rl.py when initializing the rl model 65 | ```sh 66 | tensorboard --logdir 67 | ``` 68 | This will look like 69 | ![alt tensorboard](TensorBoardScreenshot.png?raw=true "tensorboard") 70 | 71 | ## Example Usage (RLlib) 72 | The usage example is rllib_example.py and the config for freqtrade and freqtrade-gym is config_rl.json and uses IndicatorforRL.py as feature extraction. 73 | This demo is using [RLlib](https://docs.ray.io/en/master/rllib.html) to train reinforcement learning agents. 74 | Baseline can install by 75 | ```sh 76 | pip install 'ray[rllib]' 77 | ``` 78 | 79 | Run the demo to train an agent. 80 | ```sh 81 | python rllib_example.py 82 | ``` 83 | 84 | 85 | ## Example of Loading model for backtesting or trading (baseline) 86 | 87 | Move the LoadRLModel.py into user_data/strategies (you should have user_data/strategies/LoadRLModel.py) 88 | 89 | Modified the class intial load model part to your model type and path. 90 | 91 | Modified the populate_indicators and rl_model_redict method for your gym settings. 92 | 93 | Run the backtesting 94 | ```sh 95 | freqtrade backtesting -c config_rl.json -s LoadRLModel 96 | ``` 97 | 98 | Dry-run trading (remove --dry-run for real deal!) 99 | ```sh 100 | freqtrade trade --dry-run -c config_rl.json -s LoadRLModelgProto 101 | ``` 102 | 103 | 104 | ## TODO 105 | - [x] Update the strategy for loadinf the trained model for backtesting and real trading. (baseline) 106 | - [ ] The features name and total feature number(freqtradegym.py line 89) have to manually match in the indicator strategy and in freqtradegym. I would like to come up with a way to set up features in config file. 107 | - [x] RLlib example. 108 | - [ ] Update the strategy for loadinf the trained model for backtesting and real trading (RLlib). 109 | - [ ] NEAT example. 110 | 111 | # DISCLAIMER 112 | This software is for educational purposes only. Do not risk money which you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS. 113 | -------------------------------------------------------------------------------- /neat_trade.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from freqtrade.configuration import Configuration 3 | 4 | import numpy as np 5 | import datetime 6 | import pickle 7 | 8 | from functools import partial 9 | 10 | import neat 11 | import visualize 12 | from neat.parallel import ParallelEvaluator 13 | 14 | # Initialize empty configuration object 15 | fconfig = Configuration.from_files(['config_rl.json']) 16 | 17 | # Define some constants 18 | fconfig["ticker_interval"] = "5m" 19 | # Name of the strategy class 20 | fconfig["strategy"] = "IndicatorforRLFull" 21 | # Location of the data 22 | data_location = Path(fconfig['user_data_dir'], 'data', 'binance') 23 | # Pair to analyze - Only use one pair here 24 | 25 | from gym_env.trading_env import TradingEnv 26 | # from stable_baselines.deepq.policies import MlpPolicy, LnMlpPolicy 27 | 28 | fconfig['fee'] = 0.0015 29 | fconfig['timerange'] = '20170101-20200401' 30 | # fconfig['pair_whitelist'] = ["BTC/USDT"] 31 | fconfig['simulate_length'] = 60*24*30//5 32 | 33 | n = 3 34 | 35 | test_n = 100 36 | TEST_MULTIPLIER = 1 37 | T_STEPS = 10000 38 | TEST_REWARD_THRESHOLD = None 39 | 40 | ENVIRONMENT_NAME = None 41 | CONFIG_FILENAME = "./neat_config" 42 | 43 | NUM_WORKERS = 14 44 | CHECKPOINT_GENERATION_INTERVAL = 1 45 | CHECKPOINT_PREFIX = "./neat_checkpoints/" 46 | GENERATE_PLOTS = False 47 | # CHECKPOINT_FILE = "neat_checkpoints/798" 48 | CHECKPOINT_FILE = None 49 | 50 | 51 | PLOT_FILENAME_PREFIX = None 52 | MAX_GENS = 400 53 | RENDER_TESTS = False 54 | 55 | env = None 56 | 57 | config = None 58 | 59 | def _eval_genomes(eval_single_genome, genomes, neat_config): 60 | parallel_evaluator = ParallelEvaluator(NUM_WORKERS, eval_function=eval_single_genome) 61 | 62 | parallel_evaluator.evaluate(genomes, neat_config) 63 | 64 | def _run_neat(checkpoint, eval_network, eval_single_genome): 65 | # Create the population, which is the top-level object for a NEAT run. 66 | 67 | print_config_info() 68 | 69 | if checkpoint is not None: 70 | print("Resuming from checkpoint: {}".format(checkpoint)) 71 | p = neat.Checkpointer.restore_checkpoint(checkpoint) 72 | else: 73 | print("Starting run from scratch") 74 | p = neat.Population(config) 75 | 76 | stats = neat.StatisticsReporter() 77 | p.add_reporter(stats) 78 | 79 | p.add_reporter(neat.Checkpointer(CHECKPOINT_GENERATION_INTERVAL, filename_prefix=CHECKPOINT_PREFIX)) 80 | 81 | # Add a stdout reporter to show progress in the terminal. 82 | p.add_reporter(neat.StdOutReporter(False)) 83 | 84 | # Run until a solution is found. 85 | winner = p.run(partial(_eval_genomes, eval_single_genome), n=MAX_GENS) 86 | 87 | with open('winner-feedforward', 'wb') as f: 88 | pickle.dump(winner, f) 89 | 90 | # Display the winning genome. 91 | print('\nBest genome:\n{!s}'.format(winner)) 92 | 93 | net = neat.nn.FeedForwardNetwork.create(winner, config) 94 | 95 | test_genome(eval_network, net) 96 | 97 | generate_stat_plots(stats, winner) 98 | 99 | print("Finishing...") 100 | 101 | def generate_stat_plots(stats, winner): 102 | if GENERATE_PLOTS: 103 | print("Plotting stats...") 104 | visualize.draw_net(config, winner, view=False, node_names=None, filename=PLOT_FILENAME_PREFIX + "net") 105 | visualize.plot_stats(stats, ylog=False, view=False, filename=PLOT_FILENAME_PREFIX + "fitness.svg") 106 | visualize.plot_species(stats, view=False, filename=PLOT_FILENAME_PREFIX + "species.svg") 107 | 108 | 109 | def test_genome(eval_network, net): 110 | reward_goal = config.fitness_threshold if not TEST_REWARD_THRESHOLD else TEST_REWARD_THRESHOLD 111 | 112 | print("Testing genome with target average reward of: {}".format(reward_goal)) 113 | 114 | rewards = np.zeros(test_n) 115 | 116 | for i in range(test_n * TEST_MULTIPLIER): 117 | 118 | print("--> Starting test episode trial {}".format(i + 1)) 119 | observation = env.reset() 120 | action = eval_network(net, observation) 121 | 122 | done = False 123 | t = 0 124 | 125 | reward_episode = 0 126 | 127 | while not done: 128 | 129 | if RENDER_TESTS: 130 | env.render() 131 | 132 | observation, reward, done, info = env.step(action) 133 | 134 | # print("\t Observation {}: {}".format(t, observation)) 135 | # print("\t Info {}: {}".format(t, info)) 136 | 137 | action = eval_network(net, observation) 138 | 139 | reward_episode += reward 140 | 141 | # print("\t Reward {}: {}".format(t, reward)) 142 | 143 | t += 1 144 | 145 | if done: 146 | print("<-- Test episode done after {} time steps with reward {}".format(t + 1, reward_episode)) 147 | pass 148 | 149 | rewards[i % test_n] = reward_episode 150 | 151 | if i + 1 >= test_n: 152 | average_reward = np.mean(rewards) 153 | print("Average reward for episode {} is {}".format(i + 1, average_reward)) 154 | if average_reward >= reward_goal: 155 | print("Hit the desired average reward in {} episodes".format(i + 1)) 156 | break 157 | 158 | 159 | def print_config_info(): 160 | # print("Running environment: {}".format(env.spec.id)) 161 | print("Running with {} workers".format(NUM_WORKERS)) 162 | print("Running with {} episodes per genome".format(n)) 163 | print("Running with checkpoint prefix: {}".format(CHECKPOINT_PREFIX)) 164 | print("Running with {} max generations".format(MAX_GENS)) 165 | print("Running with test rendering: {}".format(RENDER_TESTS)) 166 | print("Running with config file: {}".format(CONFIG_FILENAME)) 167 | print("Running with generate_plots: {}".format(GENERATE_PLOTS)) 168 | print("Running with test multiplier: {}".format(TEST_MULTIPLIER)) 169 | print("Running with test reward threshold of: {}".format(TEST_REWARD_THRESHOLD)) 170 | 171 | 172 | def run(eval_network, eval_single_genome, environment_name): 173 | global ENVIRONMENT_NAME 174 | global CONFIG_FILENAME 175 | global env 176 | global config 177 | global CHECKPOINT_PREFIX 178 | global PLOT_FILENAME_PREFIX 179 | 180 | ENVIRONMENT_NAME = environment_name 181 | 182 | checkpoint = CHECKPOINT_FILE 183 | 184 | config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, 185 | neat.DefaultSpeciesSet, neat.DefaultStagnation, 186 | CONFIG_FILENAME) 187 | 188 | if CHECKPOINT_PREFIX is None: 189 | timestamp = datetime.datetime.utcnow().strftime('%Y_%m_%d_%H_%M_%S') 190 | CHECKPOINT_PREFIX = "cp_" + CONFIG_FILENAME.lower() + "_" + timestamp + "_gen_" 191 | 192 | if PLOT_FILENAME_PREFIX is None: 193 | timestamp = datetime.datetime.utcnow().strftime('%Y_%m_%d_%H_%M_%S') 194 | PLOT_FILENAME_PREFIX = "plot_" + CONFIG_FILENAME.lower() + "_" + timestamp + "_" 195 | 196 | _run_neat(checkpoint, eval_network, eval_single_genome) 197 | 198 | def eval_network(net, net_input): 199 | assert (len(net_input == 55)) 200 | 201 | result = np.argmax(net.activate(net_input)) 202 | 203 | assert (result == 0 or result == 1 or result == 2) 204 | 205 | return result 206 | 207 | def eval_single_genome(genome, genome_config): 208 | net = neat.nn.FeedForwardNetwork.create(genome, genome_config) 209 | total_reward = 0.0 210 | 211 | for i in range(n): 212 | # print("--> Starting new episode") 213 | observation = env.reset() 214 | 215 | action = eval_network(net, observation) 216 | 217 | done = False 218 | 219 | while not done: 220 | 221 | # env.render() 222 | 223 | observation, reward, done, info = env.step(action) 224 | 225 | # print("\t Reward {}: {}".format(t, reward)) 226 | 227 | action = eval_network(net, observation) 228 | 229 | total_reward += reward 230 | # total_reward = reward 231 | 232 | if done: 233 | # print("<-- Episode finished after {} timesteps".format(t + 1)) 234 | break 235 | 236 | return total_reward / n 237 | 238 | if __name__ == "__main__": 239 | env = TradingEnv(fconfig) 240 | obs = env.reset() 241 | 242 | # config["pair_whitelist"] = ["ETH/USDT"] 243 | # env = TradingEnv(config) 244 | # obs = env.reset() 245 | # while True: 246 | # action, _states = model.predict(obs) 247 | # obs, rewards, done, info = env.step(action) 248 | # # obs, rewards, done, info = env.step(0) 249 | # env.render() 250 | 251 | run(eval_network, eval_single_genome, environment_name="CartPole-v1") 252 | 253 | -------------------------------------------------------------------------------- /freqtradegym.py: -------------------------------------------------------------------------------- 1 | import random 2 | import json 3 | import logging 4 | import copy 5 | from datetime import datetime, timedelta 6 | from typing import Any, Dict, List, NamedTuple, Optional 7 | from pandas import DataFrame 8 | import gym 9 | from gym import spaces 10 | import pandas as pd 11 | import numpy as np 12 | import talib.abstract as ta 13 | 14 | from freqtrade.data import history 15 | from freqtrade.data.converter import trim_dataframe 16 | from freqtrade.configuration import (TimeRange, remove_credentials, 17 | validate_config_consistency) 18 | from freqtrade.resolvers import ExchangeResolver, StrategyResolver 19 | from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds 20 | from freqtrade.persistence import Trade 21 | from freqtrade.strategy.interface import IStrategy, SellCheckTuple, SellType 22 | 23 | 24 | 25 | logger = logging.getLogger(__name__) 26 | 27 | 28 | class TradingEnv(gym.Env): 29 | """A trading environment for OpenAI gym""" 30 | metadata = {'render.modes': ['human', 'system', 'none']} 31 | 32 | def __init__(self, config): 33 | super(TradingEnv, self).__init__() 34 | 35 | self.config = config 36 | self.config['strategy'] = self.config['gym_parameters']['indicator_strategy'] 37 | self.strategy = StrategyResolver.load_strategy(self.config) 38 | self.fee = self.config['gym_parameters']['fee'] 39 | self.timeframe = str(config.get('ticker_interval')) 40 | self.timeframe_min = timeframe_to_minutes(self.timeframe) 41 | self.required_startup = self.strategy.startup_candle_count 42 | 43 | data, timerange = self.load_bt_data() 44 | # need to reprocess data every time to populate signals 45 | preprocessed = self.strategy.ohlcvdata_to_dataframe(data) 46 | del data 47 | 48 | # Trim startup period from analyzed dataframe 49 | dfs = [] 50 | for pair, df in preprocessed.items(): 51 | dfs.append(trim_dataframe(df, timerange)) 52 | del preprocessed 53 | self.rest_idx = set() 54 | idx = 0 55 | for d in dfs: 56 | idx += d.shape[0] 57 | self.rest_idx.add(idx) 58 | print(self.rest_idx) 59 | 60 | df = pd.concat(dfs, ignore_index=True) 61 | del dfs 62 | 63 | # setting 64 | df = df.dropna() 65 | self.pair = pair 66 | 67 | self.ticker = self._get_ticker(df) 68 | del df 69 | 70 | self.lookback_window_size = 40 71 | 72 | # start 73 | logger.info('Using stake_currency: %s ...', self.config['stake_currency']) 74 | logger.info('Data Length: %s ...', len(self.ticker)) 75 | 76 | 77 | self.stake_amount = self.config['stake_amount'] 78 | 79 | self.reward_decay = 0.0005 80 | self.not_complete_trade_decay = 0.5 81 | self.game_loss = -0.5 82 | self.game_win = 1.0 83 | self.simulate_length = self.config['gym_parameters']['simulate_length'] 84 | 85 | # Actions 86 | self.action_space = spaces.Discrete(3) 87 | 88 | self.observation_space = spaces.Box( 89 | low=np.full(24, -np.inf), high=np.full(24, np.inf), dtype=np.float) 90 | 91 | def _next_observation(self): 92 | row = self.ticker[self.index] 93 | 94 | trad_status = 0 95 | if self.trade != None: 96 | trad_status = self.trade.calc_profit_ratio(rate=row.open) 97 | 98 | obs = np.array([ 99 | # row.open, 100 | # row.high, 101 | # row.low, 102 | # row.close, 103 | # row.volume, 104 | row.adx, 105 | row.plus_dm, 106 | row.plus_di, 107 | row.minus_dm, 108 | row.minus_di, 109 | row.aroonup, 110 | row.aroondown, 111 | row.aroonosc, 112 | row.ao, 113 | # row.kc_percent, 114 | # row.kc_width, 115 | row.uo, 116 | row.cci, 117 | row.rsi, 118 | row.fisher_rsi, 119 | row.slowd, 120 | row.slowk, 121 | row.fastd, 122 | row.fastk, 123 | row.fastd_rsi, 124 | row.fastk_rsi, 125 | row.macd, 126 | row.macdsignal, 127 | row.macdhist, 128 | row.mfi, 129 | row.roc, 130 | # row.bb_percent, 131 | # row.bb_width, 132 | # row.wbb_percent, 133 | # row.wbb_width, 134 | # row.htsine, 135 | # row.htleadsine, 136 | # row.CDLHAMMER, 137 | # row.CDLINVERTEDHAMMER, 138 | # row.CDLDRAGONFLYDOJI, 139 | # row.CDLPIERCING, 140 | # row.CDLMORNINGSTAR, 141 | # row.CDL3WHITESOLDIERS, 142 | # row.CDLHANGINGMAN, 143 | # row.CDLSHOOTINGSTAR, 144 | # row.CDLGRAVESTONEDOJI, 145 | # row.CDLDARKCLOUDCOVER, 146 | # row.CDLEVENINGDOJISTAR, 147 | # row.CDLEVENINGSTAR, 148 | # row.CDL3LINESTRIKE, 149 | # row.CDLSPINNINGTOP, 150 | # row.CDLENGULFING, 151 | # row.CDLHARAMI, 152 | # row.CDL3OUTSIDE, 153 | # row.CDL3INSIDE, 154 | ], dtype=np.float) 155 | 156 | self.status = copy.deepcopy(row) 157 | 158 | return obs 159 | 160 | def _take_action(self, action): 161 | # Hold 162 | if action == 0: 163 | return 164 | # Buy 165 | if action == 1: 166 | if self.trade == None: 167 | self.trade = Trade( 168 | pair=self.pair, 169 | open_rate=self.status.open, 170 | open_date=self.status.date, 171 | stake_amount=self.stake_amount, 172 | amount=self.stake_amount / self.status.open, 173 | fee_open=self.fee, 174 | fee_close=self.fee, 175 | is_open=True, 176 | ) 177 | self.trades.append({ 178 | "step": self.index, 179 | "type": 'buy', 180 | "total": self.status.open 181 | }) 182 | 183 | logger.debug("{} - Backtesting emulates creation of new trade: {}.".format( 184 | self.pair, self.trade)) 185 | 186 | # Sell 187 | if action == 2: 188 | if self.trade != None: 189 | profit_percent = self.trade.calc_profit_ratio(rate=self.status.open) 190 | profit_abs = self.trade.calc_profit(rate=self.status.open) 191 | self.money += profit_abs 192 | self.trade = None 193 | self._reward = profit_percent 194 | 195 | self.trades.append({ 196 | "step": self.index, 197 | "type": 'sell', 198 | "total": self.status.open 199 | }) 200 | 201 | def step(self, action): 202 | # Execute one time step within the environment 203 | self._reward = 0 204 | self._take_action(action) 205 | 206 | self.index += 1 207 | if self._reward > 1.5: 208 | self._reward = 0 209 | 210 | if self.index >= len(self.ticker): 211 | self.index = 0 212 | 213 | self.steps += 1 214 | 215 | self.total_reward += self._reward 216 | 217 | # done = (self._reward < self.game_loss) # or (self.steps > self.day_step) 218 | # done = (self.total_reward < self.game_loss) or (self.total_reward > self.game_win) or (self.steps > self.day_step) 219 | done = self.steps > self.simulate_length 220 | 221 | obs = self._next_observation() 222 | 223 | return obs, self._reward, done, {} 224 | 225 | def reset(self): 226 | # Reset the state of the environment to an initial state 227 | self.steps = 0 228 | self.index = random.randint(0, len(self.ticker)-1) 229 | 230 | self.trade = None 231 | self.trades = [] 232 | 233 | self._reward = 0 234 | self.total_reward = 0 235 | self.money = 0 236 | 237 | self.visualization = None 238 | 239 | return self._next_observation() 240 | 241 | def render(self, mode='live', close=False): 242 | # Render the environment to the screen 243 | print(f'Step: {self.index}') 244 | print(f'Reward: {self._reward}') 245 | 246 | def load_bt_data(self): 247 | timerange = TimeRange.parse_timerange(self.config['gym_parameters']['timerange']) 248 | 249 | data = history.load_data( 250 | datadir=self.config['datadir'], 251 | pairs=self.config['exchange']['pair_whitelist'], 252 | timeframe=self.timeframe, 253 | timerange=timerange, 254 | startup_candles=self.required_startup, 255 | fail_without_data=True, 256 | data_format=self.config.get('dataformat_ohlcv', 'json'), 257 | ) 258 | 259 | min_date, max_date = history.get_timerange(data) 260 | 261 | logger.info( 262 | 'Loading data from %s up to %s (%s days)..', 263 | min_date.isoformat(), max_date.isoformat(), (max_date - min_date).days 264 | ) 265 | # Adjust startts forward if not enough data is available 266 | timerange.adjust_start_if_necessary(timeframe_to_seconds(self.timeframe), 267 | self.required_startup, min_date) 268 | 269 | return data, timerange 270 | 271 | def _get_ticker(self, processed: DataFrame) -> List: 272 | processed.drop(processed.head(1).index, inplace=True) 273 | 274 | return [x for x in processed.itertuples()] 275 | 276 | -------------------------------------------------------------------------------- /LoadRLModel.py: -------------------------------------------------------------------------------- 1 | # pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement 2 | 3 | # --- Do not remove these libs --- 4 | import numpy as np # noqa 5 | import pandas as pd # noqa 6 | from pandas import DataFrame 7 | 8 | from freqtrade.strategy.interface import IStrategy 9 | 10 | # -------------------------------- 11 | # Add your lib to import here 12 | import talib.abstract as ta 13 | import freqtrade.vendor.qtpylib.indicators as qtpylib 14 | from stable_baselines import ACER 15 | 16 | # This class is a sample. Feel free to customize it. 17 | class LoadRLModel(IStrategy): 18 | stoploss = -0.50 19 | 20 | trailing_stop = False 21 | 22 | ticker_interval = '5m' 23 | 24 | # Run "populate_indicators()" only for new candle. 25 | process_only_new_candles = False 26 | 27 | startup_candle_count: int = 20 28 | 29 | model = ACER.load('model') 30 | 31 | 32 | def informative_pairs(self): 33 | return [] 34 | 35 | def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: 36 | # Momentum Indicators 37 | # ------------------------------------ 38 | 39 | # ADX 40 | dataframe['adx'] = ta.ADX(dataframe) 41 | 42 | # Plus Directional Indicator / Movement 43 | dataframe['plus_dm'] = ta.PLUS_DM(dataframe) 44 | dataframe['plus_di'] = ta.PLUS_DI(dataframe) 45 | 46 | # # Minus Directional Indicator / Movement 47 | dataframe['minus_dm'] = ta.MINUS_DM(dataframe) 48 | dataframe['minus_di'] = ta.MINUS_DI(dataframe) 49 | 50 | # Aroon, Aroon Oscillator 51 | aroon = ta.AROON(dataframe) 52 | dataframe['aroonup'] = aroon['aroonup'] 53 | dataframe['aroondown'] = aroon['aroondown'] 54 | dataframe['aroonosc'] = ta.AROONOSC(dataframe) 55 | 56 | # Awesome Oscillator 57 | dataframe['ao'] = qtpylib.awesome_oscillator(dataframe) 58 | 59 | # # Keltner Channel 60 | # keltner = qtpylib.keltner_channel(dataframe) 61 | # dataframe["kc_upperband"] = keltner["upper"] 62 | # dataframe["kc_lowerband"] = keltner["lower"] 63 | # dataframe["kc_middleband"] = keltner["mid"] 64 | # dataframe["kc_percent"] = ( 65 | # (dataframe["close"] - dataframe["kc_lowerband"]) / 66 | # (dataframe["kc_upperband"] - dataframe["kc_lowerband"]) 67 | # ) 68 | # dataframe["kc_width"] = ( 69 | # (dataframe["kc_upperband"] - dataframe["kc_lowerband"]) / dataframe["kc_middleband"] 70 | # ) 71 | 72 | # Ultimate Oscillator 73 | dataframe['uo'] = ta.ULTOSC(dataframe) 74 | 75 | # Commodity Channel Index: values [Oversold:-100, Overbought:100] 76 | dataframe['cci'] = ta.CCI(dataframe) 77 | 78 | # RSI 79 | dataframe['rsi'] = ta.RSI(dataframe) 80 | 81 | # Inverse Fisher transform on RSI: values [-1.0, 1.0] (https://goo.gl/2JGGoy) 82 | rsi = 0.1 * (dataframe['rsi'] - 50) 83 | dataframe['fisher_rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) 84 | 85 | # Inverse Fisher transform on RSI normalized: values [0.0, 100.0] (https://goo.gl/2JGGoy) 86 | dataframe['fisher_rsi_norma'] = 50 * (dataframe['fisher_rsi'] + 1) 87 | 88 | # Stochastic Slow 89 | stoch = ta.STOCH(dataframe) 90 | dataframe['slowd'] = stoch['slowd'] 91 | dataframe['slowk'] = stoch['slowk'] 92 | 93 | # Stochastic Fast 94 | stoch_fast = ta.STOCHF(dataframe) 95 | dataframe['fastd'] = stoch_fast['fastd'] 96 | dataframe['fastk'] = stoch_fast['fastk'] 97 | 98 | # Stochastic RSI 99 | stoch_rsi = ta.STOCHRSI(dataframe) 100 | dataframe['fastd_rsi'] = stoch_rsi['fastd'] 101 | dataframe['fastk_rsi'] = stoch_rsi['fastk'] 102 | 103 | # MACD 104 | macd = ta.MACD(dataframe) 105 | dataframe['macd'] = macd['macd'] 106 | dataframe['macdsignal'] = macd['macdsignal'] 107 | dataframe['macdhist'] = macd['macdhist'] 108 | 109 | # MFI 110 | dataframe['mfi'] = ta.MFI(dataframe) 111 | 112 | # # ROC 113 | dataframe['roc'] = ta.ROC(dataframe) 114 | 115 | # Overlap Studies 116 | # ------------------------------------ 117 | 118 | # # Bollinger Bands 119 | # bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2) 120 | # dataframe['bb_lowerband'] = bollinger['lower'] 121 | # dataframe['bb_middleband'] = bollinger['mid'] 122 | # dataframe['bb_upperband'] = bollinger['upper'] 123 | # dataframe["bb_percent"] = ( 124 | # (dataframe["close"] - dataframe["bb_lowerband"]) / 125 | # (dataframe["bb_upperband"] - dataframe["bb_lowerband"]) 126 | # ) 127 | # dataframe["bb_width"] = ( 128 | # (dataframe["bb_upperband"] - dataframe["bb_lowerband"]) / dataframe["bb_middleband"] 129 | # ) 130 | 131 | # # Bollinger Bands - Weighted (EMA based instead of SMA) 132 | # weighted_bollinger = qtpylib.weighted_bollinger_bands( 133 | # qtpylib.typical_price(dataframe), window=20, stds=2 134 | # ) 135 | # dataframe["wbb_upperband"] = weighted_bollinger["upper"] 136 | # dataframe["wbb_lowerband"] = weighted_bollinger["lower"] 137 | # dataframe["wbb_middleband"] = weighted_bollinger["mid"] 138 | # dataframe["wbb_percent"] = ( 139 | # (dataframe["close"] - dataframe["wbb_lowerband"]) / 140 | # (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) 141 | # ) 142 | # dataframe["wbb_width"] = ( 143 | # (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) / 144 | # dataframe["wbb_middleband"] 145 | # ) 146 | 147 | # # EMA - Exponential Moving Average 148 | # dataframe['ema3'] = ta.EMA(dataframe, timeperiod=3) 149 | # dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5) 150 | # dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10) 151 | # dataframe['ema21'] = ta.EMA(dataframe, timeperiod=21) 152 | # dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50) 153 | # dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100) 154 | 155 | # # SMA - Simple Moving Average 156 | # dataframe['sma3'] = ta.SMA(dataframe, timeperiod=3) 157 | # dataframe['sma5'] = ta.SMA(dataframe, timeperiod=5) 158 | # dataframe['sma10'] = ta.SMA(dataframe, timeperiod=10) 159 | # dataframe['sma21'] = ta.SMA(dataframe, timeperiod=21) 160 | # dataframe['sma50'] = ta.SMA(dataframe, timeperiod=50) 161 | # dataframe['sma100'] = ta.SMA(dataframe, timeperiod=100) 162 | 163 | # Parabolic SAR 164 | # dataframe['sar'] = ta.SAR(dataframe) 165 | 166 | # TEMA - Triple Exponential Moving Average 167 | # dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) 168 | 169 | # # Cycle Indicator 170 | # # ------------------------------------ 171 | # # Hilbert Transform Indicator - SineWave 172 | # hilbert = ta.HT_SINE(dataframe) 173 | # dataframe['htsine'] = hilbert['sine'] 174 | # dataframe['htleadsine'] = hilbert['leadsine'] 175 | 176 | # # Pattern Recognition - Bullish candlestick patterns 177 | # # ------------------------------------ 178 | # # Hammer: values [0, 100] 179 | # dataframe['CDLHAMMER'] = ta.CDLHAMMER(dataframe) 180 | # # Inverted Hammer: values [0, 100] 181 | # dataframe['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(dataframe) 182 | # # Dragonfly Doji: values [0, 100] 183 | # dataframe['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(dataframe) 184 | # # Piercing Line: values [0, 100] 185 | # dataframe['CDLPIERCING'] = ta.CDLPIERCING(dataframe) # values [0, 100] 186 | # # Morningstar: values [0, 100] 187 | # dataframe['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(dataframe) # values [0, 100] 188 | # # Three White Soldiers: values [0, 100] 189 | # dataframe['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(dataframe) # values [0, 100] 190 | 191 | # # Pattern Recognition - Bearish candlestick patterns 192 | # # ------------------------------------ 193 | # # Hanging Man: values [0, 100] 194 | # dataframe['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(dataframe) 195 | # # Shooting Star: values [0, 100] 196 | # dataframe['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(dataframe) 197 | # # Gravestone Doji: values [0, 100] 198 | # dataframe['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(dataframe) 199 | # # Dark Cloud Cover: values [0, 100] 200 | # dataframe['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(dataframe) 201 | # # Evening Doji Star: values [0, 100] 202 | # dataframe['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(dataframe) 203 | # # Evening Star: values [0, 100] 204 | # dataframe['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(dataframe) 205 | 206 | # # Pattern Recognition - Bullish/Bearish candlestick patterns 207 | # # ------------------------------------ 208 | # # Three Line Strike: values [0, -100, 100] 209 | # dataframe['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(dataframe) 210 | # # Spinning Top: values [0, -100, 100] 211 | # dataframe['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(dataframe) # values [0, -100, 100] 212 | # # Engulfing: values [0, -100, 100] 213 | # dataframe['CDLENGULFING'] = ta.CDLENGULFING(dataframe) # values [0, -100, 100] 214 | # # Harami: values [0, -100, 100] 215 | # dataframe['CDLHARAMI'] = ta.CDLHARAMI(dataframe) # values [0, -100, 100] 216 | # # Three Outside Up/Down: values [0, -100, 100] 217 | # dataframe['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(dataframe) # values [0, -100, 100] 218 | # # Three Inside Up/Down: values [0, -100, 100] 219 | # dataframe['CDL3INSIDE'] = ta.CDL3INSIDE(dataframe) # values [0, -100, 100] 220 | 221 | # # Chart type 222 | # # ------------------------------------ 223 | # # Heikin Ashi Strategy 224 | # heikinashi = qtpylib.heikinashi(dataframe) 225 | # dataframe['ha_open'] = heikinashi['open'] 226 | # dataframe['ha_close'] = heikinashi['close'] 227 | # dataframe['ha_high'] = heikinashi['high'] 228 | # dataframe['ha_low'] = heikinashi['low'] 229 | 230 | # Retrieve best bid and best ask from the orderbook 231 | # ------------------------------------ 232 | """ 233 | # first check if dataprovider is available 234 | if self.dp: 235 | if self.dp.runmode in ('live', 'dry_run'): 236 | ob = self.dp.orderbook(metadata['pair'], 1) 237 | dataframe['best_bid'] = ob['bids'][0][0] 238 | dataframe['best_ask'] = ob['asks'][0][0] 239 | """ 240 | 241 | return dataframe 242 | 243 | def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: 244 | """ 245 | Based on TA indicators, populates the buy signal for the given dataframe 246 | :param dataframe: DataFrame populated with indicators 247 | :param metadata: Additional information, like the currently traded pair 248 | :return: DataFrame with buy column 249 | """ 250 | # dataframe.loc[ 251 | # ( 252 | # (qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30 253 | # (dataframe['tema'] <= dataframe['bb_middleband']) & # Guard: tema below BB middle 254 | # (dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard: tema is raising 255 | # (dataframe['volume'] > 0) # Make sure Volume is not 0 256 | # ), 257 | # 'buy'] = 1 258 | action, nan_list = self.rl_model_redict(dataframe) 259 | dataframe.loc[action == 1, 'buy'] =1 260 | dataframe.loc[nan_list == True, 'buy'] = 0 261 | return dataframe 262 | 263 | def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: 264 | """ 265 | Based on TA indicators, populates the sell signal for the given dataframe 266 | :param dataframe: DataFrame populated with indicators 267 | :param metadata: Additional information, like the currently traded pair 268 | :return: DataFrame with buy column 269 | """ 270 | # dataframe.loc[ 271 | # ( 272 | # (qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70 273 | # (dataframe['tema'] > dataframe['bb_middleband']) & # Guard: tema above BB middle 274 | # (dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard: tema is falling 275 | # (dataframe['volume'] > 0) # Make sure Volume is not 0 276 | # ), 277 | # 'sell'] = 1 278 | action, nan_list = self.rl_model_redict(dataframe) 279 | dataframe.loc[action == 2, 'sell'] =1 280 | dataframe.loc[nan_list == True, 'sell'] = 0 281 | return dataframe 282 | 283 | def rl_model_redict(self, dataframe): 284 | data = np.array([ 285 | dataframe['adx'], 286 | dataframe['plus_dm'], 287 | dataframe['plus_di'], 288 | dataframe['minus_dm'], 289 | dataframe['minus_di'], 290 | dataframe['aroonup'], 291 | dataframe['aroondown'], 292 | dataframe['aroonosc'], 293 | dataframe['ao'], 294 | # dataframe['kc_percent'], 295 | # dataframe['kc_width'], 296 | dataframe['uo'], 297 | dataframe['cci'], 298 | dataframe['rsi'], 299 | dataframe['fisher_rsi'], 300 | dataframe['slowd'], 301 | dataframe['slowk'], 302 | dataframe['fastd'], 303 | dataframe['fastk'], 304 | dataframe['fastd_rsi'], 305 | dataframe['fastk_rsi'], 306 | dataframe['macd'], 307 | dataframe['macdsignal'], 308 | dataframe['macdhist'], 309 | dataframe['mfi'], 310 | dataframe['roc'], 311 | # row['bb_percent'], 312 | # row['bb_width'], 313 | # row['wbb_percent'], 314 | # row['wbb_width'], 315 | # dataframe['htsine'], 316 | # dataframe['htleadsine'], 317 | # row['CDLHAMMER'], 318 | # row['CDLINVERTEDHAMMER'], 319 | # row['CDLDRAGONFLYDOJI'], 320 | # row['CDLPIERCING'], 321 | # row['CDLMORNINGSTAR'], 322 | # row['CDL3WHITESOLDIERS'], 323 | # row['CDLHANGINGMAN'], 324 | # row['CDLSHOOTINGSTAR'], 325 | # row['CDLGRAVESTONEDOJI'], 326 | # row['CDLDARKCLOUDCOVER'], 327 | # row['CDLEVENINGDOJISTAR'], 328 | # row['CDLEVENINGSTAR'], 329 | # row['CDL3LINESTRIKE'], 330 | # row['CDLSPINNINGTOP'], 331 | # row['CDLENGULFING'], 332 | # row['CDLHARAMI'], 333 | # row['CDL3OUTSIDE'], 334 | # row['CDL3INSIDE'], 335 | # trad_status, 336 | # (self.trade != None) 337 | ], dtype=np.float) 338 | 339 | data = data.reshape(-1, 24) 340 | 341 | nan_list = np.isnan(data).any(axis=1) 342 | data = np.nan_to_num(data) 343 | action, _ = self.model.predict(data, deterministic=True) 344 | 345 | return action, nan_list 346 | -------------------------------------------------------------------------------- /IndicatorforRL.py: -------------------------------------------------------------------------------- 1 | # pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement 2 | 3 | # --- Do not remove these libs --- 4 | import numpy as np # noqa 5 | import pandas as pd # noqa 6 | from pandas import DataFrame 7 | 8 | from freqtrade.strategy.interface import IStrategy 9 | 10 | # -------------------------------- 11 | # Add your lib to import here 12 | import talib.abstract as ta 13 | import freqtrade.vendor.qtpylib.indicators as qtpylib 14 | 15 | 16 | # This class is a sample. Feel free to customize it. 17 | class IndicatorforRL(IStrategy): 18 | """ 19 | This is a sample strategy to inspire you. 20 | More information in https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-optimization.md 21 | 22 | You can: 23 | :return: a Dataframe with all mandatory indicators for the strategies 24 | - Rename the class name (Do not forget to update class_name) 25 | - Add any methods you want to build your strategy 26 | - Add any lib you need to build your strategy 27 | 28 | You must keep: 29 | - the lib in the section "Do not remove these libs" 30 | - the prototype for the methods: minimal_roi, stoploss, populate_indicators, populate_buy_trend, 31 | populate_sell_trend, hyperopt_space, buy_strategy_generator 32 | """ 33 | # Strategy interface version - allow new iterations of the strategy interface. 34 | # Check the documentation or the Sample strategy to get the latest version. 35 | INTERFACE_VERSION = 2 36 | 37 | # Minimal ROI designed for the strategy. 38 | # This attribute will be overridden if the config file contains "minimal_roi". 39 | minimal_roi = { 40 | "60": 0.01, 41 | "30": 0.02, 42 | "0": 0.04 43 | } 44 | 45 | # Optimal stoploss designed for the strategy. 46 | # This attribute will be overridden if the config file contains "stoploss". 47 | stoploss = -0.10 48 | 49 | # Trailing stoploss 50 | trailing_stop = False 51 | # trailing_only_offset_is_reached = False 52 | # trailing_stop_positive = 0.01 53 | # trailing_stop_positive_offset = 0.0 # Disabled / not configured 54 | 55 | # Optimal ticker interval for the strategy. 56 | ticker_interval = '1m' 57 | 58 | # Run "populate_indicators()" only for new candle. 59 | process_only_new_candles = False 60 | 61 | # These values can be overridden in the "ask_strategy" section in the config. 62 | use_sell_signal = True 63 | sell_profit_only = False 64 | ignore_roi_if_buy_signal = False 65 | 66 | # Number of candles the strategy requires before producing valid signals 67 | startup_candle_count: int = 20 68 | 69 | 70 | def informative_pairs(self): 71 | """ 72 | Define additional, informative pair/interval combinations to be cached from the exchange. 73 | These pair/interval combinations are non-tradeable, unless they are part 74 | of the whitelist as well. 75 | For more information, please consult the documentation 76 | :return: List of tuples in the format (pair, interval) 77 | Sample: return [("ETH/USDT", "5m"), 78 | ("BTC/USDT", "15m"), 79 | ] 80 | """ 81 | return [] 82 | 83 | def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: 84 | """ 85 | Adds several different TA indicators to the given DataFrame 86 | 87 | Performance Note: For the best performance be frugal on the number of indicators 88 | you are using. Let uncomment only the indicator you are using in your strategies 89 | or your hyperopt configuration, otherwise you will waste your memory and CPU usage. 90 | :param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe() 91 | :param metadata: Additional information, like the currently traded pair 92 | :return: a Dataframe with all mandatory indicators for the strategies 93 | """ 94 | 95 | # Momentum Indicators 96 | # ------------------------------------ 97 | 98 | # ADX 99 | dataframe['adx'] = ta.ADX(dataframe) 100 | 101 | # Plus Directional Indicator / Movement 102 | dataframe['plus_dm'] = ta.PLUS_DM(dataframe) 103 | dataframe['plus_di'] = ta.PLUS_DI(dataframe) 104 | 105 | # # Minus Directional Indicator / Movement 106 | dataframe['minus_dm'] = ta.MINUS_DM(dataframe) 107 | dataframe['minus_di'] = ta.MINUS_DI(dataframe) 108 | 109 | # Aroon, Aroon Oscillator 110 | aroon = ta.AROON(dataframe) 111 | dataframe['aroonup'] = aroon['aroonup'] 112 | dataframe['aroondown'] = aroon['aroondown'] 113 | dataframe['aroonosc'] = ta.AROONOSC(dataframe) 114 | 115 | # Awesome Oscillator 116 | dataframe['ao'] = qtpylib.awesome_oscillator(dataframe) 117 | 118 | # # Keltner Channel 119 | # keltner = qtpylib.keltner_channel(dataframe) 120 | # dataframe["kc_upperband"] = keltner["upper"] 121 | # dataframe["kc_lowerband"] = keltner["lower"] 122 | # dataframe["kc_middleband"] = keltner["mid"] 123 | # dataframe["kc_percent"] = ( 124 | # (dataframe["close"] - dataframe["kc_lowerband"]) / 125 | # (dataframe["kc_upperband"] - dataframe["kc_lowerband"]) 126 | # ) 127 | # dataframe["kc_width"] = ( 128 | # (dataframe["kc_upperband"] - dataframe["kc_lowerband"]) / dataframe["kc_middleband"] 129 | # ) 130 | 131 | # Ultimate Oscillator 132 | dataframe['uo'] = ta.ULTOSC(dataframe) 133 | 134 | # Commodity Channel Index: values [Oversold:-100, Overbought:100] 135 | dataframe['cci'] = ta.CCI(dataframe) 136 | 137 | # RSI 138 | dataframe['rsi'] = ta.RSI(dataframe) 139 | 140 | # Inverse Fisher transform on RSI: values [-1.0, 1.0] (https://goo.gl/2JGGoy) 141 | rsi = 0.1 * (dataframe['rsi'] - 50) 142 | dataframe['fisher_rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) 143 | 144 | # Inverse Fisher transform on RSI normalized: values [0.0, 100.0] (https://goo.gl/2JGGoy) 145 | dataframe['fisher_rsi_norma'] = 50 * (dataframe['fisher_rsi'] + 1) 146 | 147 | # Stochastic Slow 148 | stoch = ta.STOCH(dataframe) 149 | dataframe['slowd'] = stoch['slowd'] 150 | dataframe['slowk'] = stoch['slowk'] 151 | 152 | # Stochastic Fast 153 | stoch_fast = ta.STOCHF(dataframe) 154 | dataframe['fastd'] = stoch_fast['fastd'] 155 | dataframe['fastk'] = stoch_fast['fastk'] 156 | 157 | # Stochastic RSI 158 | stoch_rsi = ta.STOCHRSI(dataframe) 159 | dataframe['fastd_rsi'] = stoch_rsi['fastd'] 160 | dataframe['fastk_rsi'] = stoch_rsi['fastk'] 161 | 162 | # MACD 163 | macd = ta.MACD(dataframe) 164 | dataframe['macd'] = macd['macd'] 165 | dataframe['macdsignal'] = macd['macdsignal'] 166 | dataframe['macdhist'] = macd['macdhist'] 167 | 168 | # MFI 169 | dataframe['mfi'] = ta.MFI(dataframe) 170 | 171 | # # ROC 172 | dataframe['roc'] = ta.ROC(dataframe) 173 | 174 | # Overlap Studies 175 | # ------------------------------------ 176 | 177 | # # Bollinger Bands 178 | # bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2) 179 | # dataframe['bb_lowerband'] = bollinger['lower'] 180 | # dataframe['bb_middleband'] = bollinger['mid'] 181 | # dataframe['bb_upperband'] = bollinger['upper'] 182 | # dataframe["bb_percent"] = ( 183 | # (dataframe["close"] - dataframe["bb_lowerband"]) / 184 | # (dataframe["bb_upperband"] - dataframe["bb_lowerband"]) 185 | # ) 186 | # dataframe["bb_width"] = ( 187 | # (dataframe["bb_upperband"] - dataframe["bb_lowerband"]) / dataframe["bb_middleband"] 188 | # ) 189 | 190 | # # Bollinger Bands - Weighted (EMA based instead of SMA) 191 | # weighted_bollinger = qtpylib.weighted_bollinger_bands( 192 | # qtpylib.typical_price(dataframe), window=20, stds=2 193 | # ) 194 | # dataframe["wbb_upperband"] = weighted_bollinger["upper"] 195 | # dataframe["wbb_lowerband"] = weighted_bollinger["lower"] 196 | # dataframe["wbb_middleband"] = weighted_bollinger["mid"] 197 | # dataframe["wbb_percent"] = ( 198 | # (dataframe["close"] - dataframe["wbb_lowerband"]) / 199 | # (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) 200 | # ) 201 | # dataframe["wbb_width"] = ( 202 | # (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) / 203 | # dataframe["wbb_middleband"] 204 | # ) 205 | 206 | # # EMA - Exponential Moving Average 207 | # dataframe['ema3'] = ta.EMA(dataframe, timeperiod=3) 208 | # dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5) 209 | # dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10) 210 | # dataframe['ema21'] = ta.EMA(dataframe, timeperiod=21) 211 | # dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50) 212 | # dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100) 213 | 214 | # # SMA - Simple Moving Average 215 | # dataframe['sma3'] = ta.SMA(dataframe, timeperiod=3) 216 | # dataframe['sma5'] = ta.SMA(dataframe, timeperiod=5) 217 | # dataframe['sma10'] = ta.SMA(dataframe, timeperiod=10) 218 | # dataframe['sma21'] = ta.SMA(dataframe, timeperiod=21) 219 | # dataframe['sma50'] = ta.SMA(dataframe, timeperiod=50) 220 | # dataframe['sma100'] = ta.SMA(dataframe, timeperiod=100) 221 | 222 | # Parabolic SAR 223 | # dataframe['sar'] = ta.SAR(dataframe) 224 | 225 | # TEMA - Triple Exponential Moving Average 226 | # dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) 227 | 228 | # # Cycle Indicator 229 | # # ------------------------------------ 230 | # # Hilbert Transform Indicator - SineWave 231 | # hilbert = ta.HT_SINE(dataframe) 232 | # dataframe['htsine'] = hilbert['sine'] 233 | # dataframe['htleadsine'] = hilbert['leadsine'] 234 | 235 | # # Pattern Recognition - Bullish candlestick patterns 236 | # # ------------------------------------ 237 | # # Hammer: values [0, 100] 238 | # dataframe['CDLHAMMER'] = ta.CDLHAMMER(dataframe) 239 | # # Inverted Hammer: values [0, 100] 240 | # dataframe['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(dataframe) 241 | # # Dragonfly Doji: values [0, 100] 242 | # dataframe['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(dataframe) 243 | # # Piercing Line: values [0, 100] 244 | # dataframe['CDLPIERCING'] = ta.CDLPIERCING(dataframe) # values [0, 100] 245 | # # Morningstar: values [0, 100] 246 | # dataframe['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(dataframe) # values [0, 100] 247 | # # Three White Soldiers: values [0, 100] 248 | # dataframe['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(dataframe) # values [0, 100] 249 | 250 | # # Pattern Recognition - Bearish candlestick patterns 251 | # # ------------------------------------ 252 | # # Hanging Man: values [0, 100] 253 | # dataframe['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(dataframe) 254 | # # Shooting Star: values [0, 100] 255 | # dataframe['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(dataframe) 256 | # # Gravestone Doji: values [0, 100] 257 | # dataframe['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(dataframe) 258 | # # Dark Cloud Cover: values [0, 100] 259 | # dataframe['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(dataframe) 260 | # # Evening Doji Star: values [0, 100] 261 | # dataframe['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(dataframe) 262 | # # Evening Star: values [0, 100] 263 | # dataframe['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(dataframe) 264 | 265 | # # Pattern Recognition - Bullish/Bearish candlestick patterns 266 | # # ------------------------------------ 267 | # # Three Line Strike: values [0, -100, 100] 268 | # dataframe['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(dataframe) 269 | # # Spinning Top: values [0, -100, 100] 270 | # dataframe['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(dataframe) # values [0, -100, 100] 271 | # # Engulfing: values [0, -100, 100] 272 | # dataframe['CDLENGULFING'] = ta.CDLENGULFING(dataframe) # values [0, -100, 100] 273 | # # Harami: values [0, -100, 100] 274 | # dataframe['CDLHARAMI'] = ta.CDLHARAMI(dataframe) # values [0, -100, 100] 275 | # # Three Outside Up/Down: values [0, -100, 100] 276 | # dataframe['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(dataframe) # values [0, -100, 100] 277 | # # Three Inside Up/Down: values [0, -100, 100] 278 | # dataframe['CDL3INSIDE'] = ta.CDL3INSIDE(dataframe) # values [0, -100, 100] 279 | 280 | # # Chart type 281 | # # ------------------------------------ 282 | # # Heikin Ashi Strategy 283 | # heikinashi = qtpylib.heikinashi(dataframe) 284 | # dataframe['ha_open'] = heikinashi['open'] 285 | # dataframe['ha_close'] = heikinashi['close'] 286 | # dataframe['ha_high'] = heikinashi['high'] 287 | # dataframe['ha_low'] = heikinashi['low'] 288 | 289 | # Retrieve best bid and best ask from the orderbook 290 | # ------------------------------------ 291 | """ 292 | # first check if dataprovider is available 293 | if self.dp: 294 | if self.dp.runmode in ('live', 'dry_run'): 295 | ob = self.dp.orderbook(metadata['pair'], 1) 296 | dataframe['best_bid'] = ob['bids'][0][0] 297 | dataframe['best_ask'] = ob['asks'][0][0] 298 | """ 299 | 300 | return dataframe 301 | 302 | def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: 303 | """ 304 | Based on TA indicators, populates the buy signal for the given dataframe 305 | :param dataframe: DataFrame populated with indicators 306 | :param metadata: Additional information, like the currently traded pair 307 | :return: DataFrame with buy column 308 | """ 309 | dataframe.loc[ 310 | ( 311 | (qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30 312 | (dataframe['tema'] <= dataframe['bb_middleband']) & # Guard: tema below BB middle 313 | (dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard: tema is raising 314 | (dataframe['volume'] > 0) # Make sure Volume is not 0 315 | ), 316 | 'buy'] = 1 317 | 318 | return dataframe 319 | 320 | def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: 321 | """ 322 | Based on TA indicators, populates the sell signal for the given dataframe 323 | :param dataframe: DataFrame populated with indicators 324 | :param metadata: Additional information, like the currently traded pair 325 | :return: DataFrame with buy column 326 | """ 327 | dataframe.loc[ 328 | ( 329 | (qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70 330 | (dataframe['tema'] > dataframe['bb_middleband']) & # Guard: tema above BB middle 331 | (dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard: tema is falling 332 | (dataframe['volume'] > 0) # Make sure Volume is not 0 333 | ), 334 | 'sell'] = 1 335 | return dataframe 336 | -------------------------------------------------------------------------------- /Neat_RL.py: -------------------------------------------------------------------------------- 1 | # pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement 2 | 3 | # --- Do not remove these libs --- 4 | import numpy as np # noqa 5 | import pandas as pd # noqa 6 | from pandas import DataFrame 7 | 8 | from freqtrade.strategy.interface import IStrategy 9 | 10 | # -------------------------------- 11 | # Add your lib to import here 12 | import talib.abstract as ta 13 | import freqtrade.vendor.qtpylib.indicators as qtpylib 14 | import neat 15 | import pickle 16 | 17 | # This class is a sample. Feel free to customize it. 18 | class Neat_RL(IStrategy): 19 | """ 20 | This is a sample strategy to inspire you. 21 | More information in https://github.com/freqtrade/freqtrade/blob/develop/docs/bot-optimization.md 22 | 23 | You can: 24 | :return: a Dataframe with all mandatory indicators for the strategies 25 | - Rename the class name (Do not forget to update class_name) 26 | - Add any methods you want to build your strategy 27 | - Add any lib you need to build your strategy 28 | 29 | You must keep: 30 | - the lib in the section "Do not remove these libs" 31 | - the prototype for the methods: minimal_roi, stoploss, populate_indicators, populate_buy_trend, 32 | populate_sell_trend, hyperopt_space, buy_strategy_generator 33 | """ 34 | # Strategy interface version - allow new iterations of the strategy interface. 35 | # Check the documentation or the Sample strategy to get the latest version. 36 | # INTERFACE_VERSION = 2 37 | 38 | # Minimal ROI designed for the strategy. 39 | # This attribute will be overridden if the config file contains "minimal_roi". 40 | # minimal_roi = { 41 | # "60": 0.01, 42 | # "30": 0.02, 43 | # "0": 0.04 44 | # } 45 | 46 | # Optimal stoploss designed for the strategy. 47 | # This attribute will be overridden if the config file contains "stoploss". 48 | # stoploss = -10 49 | stoploss = -0.50 50 | 51 | # Trailing stoploss 52 | trailing_stop = False 53 | # trailing_only_offset_is_reached = False 54 | # trailing_stop_positive = 0.01 55 | # trailing_stop_positive_offset = 0.0 # Disabled / not configured 56 | 57 | # Optimal ticker interval for the strategy. 58 | ticker_interval = '5m' 59 | 60 | # Run "populate_indicators()" only for new candle. 61 | process_only_new_candles = False 62 | 63 | # These values can be overridden in the "ask_strategy" section in the config. 64 | # use_sell_signal = True 65 | # sell_profit_only = False 66 | # ignore_roi_if_buy_signal = False 67 | 68 | # Number of candles the strategy requires before producing valid signals 69 | startup_candle_count: int = 20 70 | 71 | with open('winner-feedforward', 'rb') as f: 72 | nc = pickle.load(f) 73 | 74 | # print(nc) 75 | 76 | nconfig = neat.Config( 77 | neat.DefaultGenome, 78 | neat.DefaultReproduction, 79 | neat.DefaultSpeciesSet, 80 | neat.DefaultStagnation, 81 | "neat_config" 82 | ) 83 | 84 | model = neat.nn.FeedForwardNetwork.create(nc, nconfig) 85 | 86 | def informative_pairs(self): 87 | """ 88 | Define additional, informative pair/interval combinations to be cached from the exchange. 89 | These pair/interval combinations are non-tradeable, unless they are part 90 | of the whitelist as well. 91 | For more information, please consult the documentation 92 | :return: List of tuples in the format (pair, interval) 93 | Sample: return [("ETH/USDT", "5m"), 94 | ("BTC/USDT", "15m"), 95 | ] 96 | """ 97 | return [] 98 | 99 | def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: 100 | """ 101 | Adds several different TA indicators to the given DataFrame 102 | 103 | Performance Note: For the best performance be frugal on the number of indicators 104 | you are using. Let uncomment only the indicator you are using in your strategies 105 | or your hyperopt configuration, otherwise you will waste your memory and CPU usage. 106 | :param dataframe: Raw data from the exchange and parsed by parse_ticker_dataframe() 107 | :param metadata: Additional information, like the currently traded pair 108 | :return: a Dataframe with all mandatory indicators for the strategies 109 | """ 110 | 111 | # Momentum Indicators 112 | # ------------------------------------ 113 | 114 | # ADX 115 | dataframe['adx'] = ta.ADX(dataframe) 116 | 117 | # Plus Directional Indicator / Movement 118 | dataframe['plus_dm'] = ta.PLUS_DM(dataframe) 119 | dataframe['plus_di'] = ta.PLUS_DI(dataframe) 120 | 121 | # # Minus Directional Indicator / Movement 122 | dataframe['minus_dm'] = ta.MINUS_DM(dataframe) 123 | dataframe['minus_di'] = ta.MINUS_DI(dataframe) 124 | 125 | # Aroon, Aroon Oscillator 126 | aroon = ta.AROON(dataframe) 127 | dataframe['aroonup'] = aroon['aroonup'] 128 | dataframe['aroondown'] = aroon['aroondown'] 129 | dataframe['aroonosc'] = ta.AROONOSC(dataframe) 130 | 131 | # Awesome Oscillator 132 | dataframe['ao'] = qtpylib.awesome_oscillator(dataframe) 133 | 134 | # Keltner Channel 135 | keltner = qtpylib.keltner_channel(dataframe) 136 | dataframe["kc_upperband"] = keltner["upper"] 137 | dataframe["kc_lowerband"] = keltner["lower"] 138 | dataframe["kc_middleband"] = keltner["mid"] 139 | dataframe["kc_percent"] = ( 140 | (dataframe["close"] - dataframe["kc_lowerband"]) / 141 | (dataframe["kc_upperband"] - dataframe["kc_lowerband"]) 142 | ) 143 | dataframe["kc_width"] = ( 144 | (dataframe["kc_upperband"] - dataframe["kc_lowerband"]) / dataframe["kc_middleband"] 145 | ) 146 | 147 | # Ultimate Oscillator 148 | dataframe['uo'] = ta.ULTOSC(dataframe) 149 | 150 | # Commodity Channel Index: values [Oversold:-100, Overbought:100] 151 | dataframe['cci'] = ta.CCI(dataframe) 152 | 153 | # RSI 154 | dataframe['rsi'] = ta.RSI(dataframe) 155 | 156 | # Inverse Fisher transform on RSI: values [-1.0, 1.0] (https://goo.gl/2JGGoy) 157 | rsi = 0.1 * (dataframe['rsi'] - 50) 158 | dataframe['fisher_rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) 159 | 160 | # Inverse Fisher transform on RSI normalized: values [0.0, 100.0] (https://goo.gl/2JGGoy) 161 | dataframe['fisher_rsi_norma'] = 50 * (dataframe['fisher_rsi'] + 1) 162 | 163 | # Stochastic Slow 164 | stoch = ta.STOCH(dataframe) 165 | dataframe['slowd'] = stoch['slowd'] 166 | dataframe['slowk'] = stoch['slowk'] 167 | 168 | # Stochastic Fast 169 | stoch_fast = ta.STOCHF(dataframe) 170 | dataframe['fastd'] = stoch_fast['fastd'] 171 | dataframe['fastk'] = stoch_fast['fastk'] 172 | 173 | # Stochastic RSI 174 | stoch_rsi = ta.STOCHRSI(dataframe) 175 | dataframe['fastd_rsi'] = stoch_rsi['fastd'] 176 | dataframe['fastk_rsi'] = stoch_rsi['fastk'] 177 | 178 | # MACD 179 | macd = ta.MACD(dataframe) 180 | dataframe['macd'] = macd['macd'] 181 | dataframe['macdsignal'] = macd['macdsignal'] 182 | dataframe['macdhist'] = macd['macdhist'] 183 | 184 | # MFI 185 | dataframe['mfi'] = ta.MFI(dataframe) 186 | 187 | # # ROC 188 | dataframe['roc'] = ta.ROC(dataframe) 189 | 190 | # Overlap Studies 191 | # ------------------------------------ 192 | 193 | # Bollinger Bands 194 | bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2) 195 | dataframe['bb_lowerband'] = bollinger['lower'] 196 | dataframe['bb_middleband'] = bollinger['mid'] 197 | dataframe['bb_upperband'] = bollinger['upper'] 198 | dataframe["bb_percent"] = ( 199 | (dataframe["close"] - dataframe["bb_lowerband"]) / 200 | (dataframe["bb_upperband"] - dataframe["bb_lowerband"]) 201 | ) 202 | dataframe["bb_width"] = ( 203 | (dataframe["bb_upperband"] - dataframe["bb_lowerband"]) / dataframe["bb_middleband"] 204 | ) 205 | 206 | # Bollinger Bands - Weighted (EMA based instead of SMA) 207 | weighted_bollinger = qtpylib.weighted_bollinger_bands( 208 | qtpylib.typical_price(dataframe), window=20, stds=2 209 | ) 210 | dataframe["wbb_upperband"] = weighted_bollinger["upper"] 211 | dataframe["wbb_lowerband"] = weighted_bollinger["lower"] 212 | dataframe["wbb_middleband"] = weighted_bollinger["mid"] 213 | dataframe["wbb_percent"] = ( 214 | (dataframe["close"] - dataframe["wbb_lowerband"]) / 215 | (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) 216 | ) 217 | dataframe["wbb_width"] = ( 218 | (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) / 219 | dataframe["wbb_middleband"] 220 | ) 221 | 222 | # EMA - Exponential Moving Average 223 | dataframe['ema3'] = ta.EMA(dataframe, timeperiod=3) 224 | dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5) 225 | dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10) 226 | dataframe['ema21'] = ta.EMA(dataframe, timeperiod=21) 227 | dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50) 228 | dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100) 229 | 230 | # SMA - Simple Moving Average 231 | dataframe['sma3'] = ta.SMA(dataframe, timeperiod=3) 232 | dataframe['sma5'] = ta.SMA(dataframe, timeperiod=5) 233 | dataframe['sma10'] = ta.SMA(dataframe, timeperiod=10) 234 | dataframe['sma21'] = ta.SMA(dataframe, timeperiod=21) 235 | dataframe['sma50'] = ta.SMA(dataframe, timeperiod=50) 236 | dataframe['sma100'] = ta.SMA(dataframe, timeperiod=100) 237 | 238 | # Parabolic SAR 239 | dataframe['sar'] = ta.SAR(dataframe) 240 | 241 | # TEMA - Triple Exponential Moving Average 242 | dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9) 243 | 244 | # Cycle Indicator 245 | # ------------------------------------ 246 | # Hilbert Transform Indicator - SineWave 247 | hilbert = ta.HT_SINE(dataframe) 248 | dataframe['htsine'] = hilbert['sine'] 249 | dataframe['htleadsine'] = hilbert['leadsine'] 250 | 251 | # Pattern Recognition - Bullish candlestick patterns 252 | # ------------------------------------ 253 | # Hammer: values [0, 100] 254 | dataframe['CDLHAMMER'] = ta.CDLHAMMER(dataframe) 255 | # Inverted Hammer: values [0, 100] 256 | dataframe['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(dataframe) 257 | # Dragonfly Doji: values [0, 100] 258 | dataframe['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(dataframe) 259 | # Piercing Line: values [0, 100] 260 | dataframe['CDLPIERCING'] = ta.CDLPIERCING(dataframe) # values [0, 100] 261 | # Morningstar: values [0, 100] 262 | dataframe['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(dataframe) # values [0, 100] 263 | # Three White Soldiers: values [0, 100] 264 | dataframe['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(dataframe) # values [0, 100] 265 | 266 | # Pattern Recognition - Bearish candlestick patterns 267 | # ------------------------------------ 268 | # Hanging Man: values [0, 100] 269 | dataframe['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(dataframe) 270 | # Shooting Star: values [0, 100] 271 | dataframe['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(dataframe) 272 | # Gravestone Doji: values [0, 100] 273 | dataframe['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(dataframe) 274 | # Dark Cloud Cover: values [0, 100] 275 | dataframe['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(dataframe) 276 | # Evening Doji Star: values [0, 100] 277 | dataframe['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(dataframe) 278 | # Evening Star: values [0, 100] 279 | dataframe['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(dataframe) 280 | 281 | # Pattern Recognition - Bullish/Bearish candlestick patterns 282 | # ------------------------------------ 283 | # Three Line Strike: values [0, -100, 100] 284 | dataframe['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(dataframe) 285 | # Spinning Top: values [0, -100, 100] 286 | dataframe['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(dataframe) # values [0, -100, 100] 287 | # Engulfing: values [0, -100, 100] 288 | dataframe['CDLENGULFING'] = ta.CDLENGULFING(dataframe) # values [0, -100, 100] 289 | # Harami: values [0, -100, 100] 290 | dataframe['CDLHARAMI'] = ta.CDLHARAMI(dataframe) # values [0, -100, 100] 291 | # Three Outside Up/Down: values [0, -100, 100] 292 | dataframe['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(dataframe) # values [0, -100, 100] 293 | # Three Inside Up/Down: values [0, -100, 100] 294 | dataframe['CDL3INSIDE'] = ta.CDL3INSIDE(dataframe) # values [0, -100, 100] 295 | 296 | # Chart type 297 | # ------------------------------------ 298 | # Heikin Ashi Strategy 299 | heikinashi = qtpylib.heikinashi(dataframe) 300 | dataframe['ha_open'] = heikinashi['open'] 301 | dataframe['ha_close'] = heikinashi['close'] 302 | dataframe['ha_high'] = heikinashi['high'] 303 | dataframe['ha_low'] = heikinashi['low'] 304 | 305 | # Retrieve best bid and best ask from the orderbook 306 | # ------------------------------------ 307 | """ 308 | # first check if dataprovider is available 309 | if self.dp: 310 | if self.dp.runmode in ('live', 'dry_run'): 311 | ob = self.dp.orderbook(metadata['pair'], 1) 312 | dataframe['best_bid'] = ob['bids'][0][0] 313 | dataframe['best_ask'] = ob['asks'][0][0] 314 | """ 315 | 316 | return dataframe 317 | 318 | def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: 319 | """ 320 | Based on TA indicators, populates the buy signal for the given dataframe 321 | :param dataframe: DataFrame populated with indicators 322 | :param metadata: Additional information, like the currently traded pair 323 | :return: DataFrame with buy column 324 | """ 325 | # dataframe.loc[ 326 | # ( 327 | # (qtpylib.crossed_above(dataframe['rsi'], 30)) & # Signal: RSI crosses above 30 328 | # (dataframe['tema'] <= dataframe['bb_middleband']) & # Guard: tema below BB middle 329 | # (dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard: tema is raising 330 | # (dataframe['volume'] > 0) # Make sure Volume is not 0 331 | # ), 332 | # 'buy'] = 1 333 | action, nan_list = self.rl_model_redict(dataframe) 334 | dataframe.loc[action == 1, 'buy'] =1 335 | # dataframe.loc[nan_list == True, 'buy'] = 0 336 | return dataframe 337 | 338 | def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: 339 | """ 340 | Based on TA indicators, populates the sell signal for the given dataframe 341 | :param dataframe: DataFrame populated with indicators 342 | :param metadata: Additional information, like the currently traded pair 343 | :return: DataFrame with buy column 344 | """ 345 | # dataframe.loc[ 346 | # ( 347 | # (qtpylib.crossed_above(dataframe['rsi'], 70)) & # Signal: RSI crosses above 70 348 | # (dataframe['tema'] > dataframe['bb_middleband']) & # Guard: tema above BB middle 349 | # (dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard: tema is falling 350 | # (dataframe['volume'] > 0) # Make sure Volume is not 0 351 | # ), 352 | # 'sell'] = 1 353 | action, nan_list = self.rl_model_redict(dataframe) 354 | dataframe.loc[action == 2, 'sell'] =1 355 | # dataframe.loc[nan_list == True, 'sell'] = 0 356 | return dataframe 357 | 358 | def rl_model_redict(self, dataframe): 359 | data = np.array([ 360 | dataframe['adx'], 361 | dataframe['plus_dm'], 362 | dataframe['plus_di'], 363 | dataframe['minus_dm'], 364 | dataframe['minus_di'], 365 | dataframe['aroonup'], 366 | dataframe['aroondown'], 367 | dataframe['aroonosc'], 368 | dataframe['ao'], 369 | dataframe['kc_percent'], 370 | dataframe['kc_width'], 371 | dataframe['uo'], 372 | dataframe['cci'], 373 | dataframe['rsi'], 374 | dataframe['fisher_rsi'], 375 | dataframe['slowd'], 376 | dataframe['slowk'], 377 | dataframe['fastd'], 378 | dataframe['fastk'], 379 | dataframe['fastd_rsi'], 380 | dataframe['fastk_rsi'], 381 | dataframe['macd'], 382 | dataframe['macdsignal'], 383 | dataframe['macdhist'], 384 | dataframe['mfi'], 385 | dataframe['roc'], 386 | dataframe['bb_percent'], 387 | dataframe['bb_width'], 388 | dataframe['wbb_percent'], 389 | dataframe['wbb_width'], 390 | dataframe['htsine'], 391 | dataframe['htleadsine'], 392 | dataframe['CDLHAMMER'], 393 | dataframe['CDLINVERTEDHAMMER'], 394 | dataframe['CDLDRAGONFLYDOJI'], 395 | dataframe['CDLPIERCING'], 396 | dataframe['CDLMORNINGSTAR'], 397 | dataframe['CDL3WHITESOLDIERS'], 398 | dataframe['CDLHANGINGMAN'], 399 | dataframe['CDLSHOOTINGSTAR'], 400 | dataframe['CDLGRAVESTONEDOJI'], 401 | dataframe['CDLDARKCLOUDCOVER'], 402 | dataframe['CDLEVENINGDOJISTAR'], 403 | dataframe['CDLEVENINGSTAR'], 404 | dataframe['CDL3LINESTRIKE'], 405 | dataframe['CDLSPINNINGTOP'], 406 | dataframe['CDLENGULFING'], 407 | dataframe['CDLHARAMI'], 408 | dataframe['CDL3OUTSIDE'], 409 | dataframe['CDL3INSIDE'], 410 | # trad_status, 411 | # (self.trade != None) 412 | ], dtype=np.float) 413 | 414 | data = data.reshape(-1, 55) 415 | 416 | nan_list = np.isnan(data).any(axis=1) 417 | data = np.nan_to_num(data) 418 | # action, _ = self.model.predict(data, deterministic=True) 419 | actions = [] 420 | for d in data: 421 | pred = self.model.activate(d) 422 | actions.append(np.argmax(pred)) 423 | actions = np.array(actions) 424 | # print(actions) 425 | return actions, nan_list 426 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------