Created
February 8, 2022 15:14
-
-
Save yigitcetin/f4f38e8f125a4c6899594d423736bf8e to your computer and use it in GitHub Desktop.
RSI Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Calculate RSI | |
df['RSI'] = df.ta.rsi(close='Close', length=14, append=True) | |
# Add values to a list | |
stats.append(df.loc[df.shape[0] - 2, 'RSI']) | |
return stats, trend_dir | |
... | |
... | |
... | |
... | |
## <<<<<<<<<<< START LOOP HERE >>>>>>>>>>>>>>>>> | |
RSI = unfiltered_stats[6] | |
if ADX > 25 and (ADX_Slope > 0 and ((DM_plus > DM_minus and ADX > DM_minus) or ( | |
ADX < DM_plus and ADX < DM_minus))) and DM_plus > DM_minus and RSI < 50 and trend_direction == "up": | |
unfiltered_stats.append("long") | |
unsorted_tradable_perps.append(unfiltered_stats) | |
elif ADX > 25 and (ADX_Slope > 0 and ((DM_plus < DM_minus and ADX > DM_plus) or ( | |
ADX < DM_plus and ADX < DM_minus))) and DM_plus < DM_minus and RSI > 50 and trend_direction == "down": | |
unfiltered_stats.append("short") | |
unsorted_tradable_perps.append(unfiltered_stats) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sure @rhazeleger, what kind of error dou you get? You can find It below but I think code is not working because I run it for 6 hours and doesn't enter to any long or short positions.
`import ccxt
import time
import math
import config
import sys
from time import gmtime, strftime
from py3cw.request import Py3CW
from pathlib import Path
from datetime import timezone
import datetime
import numpy as np
import pandas as pd
import pandas_ta as ta
import operator
Setup
p3cw = Py3CW(
key=config.TC_API_KEY,
secret=config.TC_API_SECRET,
request_options={
'request_timeout': 30,
'nr_of_retries': 5,
'retry_status_codes': [500, 502, 503, 504]
}
)
ftx = ccxt.ftx({
'apiKey': config.API_KEY,
'secret': config.SECRET_KEY,
'headers': {'FTX-SUBACCOUNT': config.SUB_ACCOUNT}
})
ftx.verbose = True
def get_markets():
trycnt = 4
while trycnt > 0:
try:
all_markets = ftx.load_markets(True)
trycnt = 0
except Exception as e:
print("Connection error, trying again...")
f = open("3ctrigger_log.txt", "a")
f.write(f'FTX cononnection error at {strftime("%Y-%m-%d %H:%M:%S", gmtime())} UTC\n')
f.close()
trycnt -= 1
if trycnt == 3:
time.sleep(3)
elif trycnt == 2:
time.sleep(15)
elif trycnt == 1:
time.sleep(45)
else:
return all_markets
def get_tradeable_balance():
trycnt = 4
while trycnt > 0:
try:
account_balances = ftx.fetch_balance()
balance = account_balances["total"]["USD"]
print(f'Balance: {balance}')
trycnt = 0
except Exception as e:
print("Connection error, trying again...")
f = open("3ctrigger_log.txt", "a")
f.write(f'FTX cononnection error at {strftime("%Y-%m-%d %H:%M:%S", gmtime())} UTC\n')
f.close()
trycnt -= 1
if trycnt == 3:
time.sleep(3)
elif trycnt == 2:
time.sleep(15)
elif trycnt == 1:
time.sleep(45)
else:
return balance
def start_bot(pair, ids):
bot_id = ids[pair]
f = open("3ctrigger_log.txt", "a")
f.write(f'Enable bot for {pair} at {strftime("%Y-%m-%d %H:%M:%S", gmtime())} UTC\n')
f.close()
error, bot_trigger = p3cw.request(
entity='bots',
action='enable',
action_id=bot_id
)
print(f'Bot Enabled for {pair} - {bot_id}')
return bot_trigger
def close_deal(pair, bot_id):
if type(bot_id) is not int:
bot_id = bot_id[pair]
f = open("3ctrigger_log.txt", "a")
f.write(f'Panic Close - {pair} - {bot_id} at {strftime("%Y-%m-%d %H:%M:%S", gmtime())} UTC\n')
f.close()
error, deal_close = p3cw.request(
entity='bots',
action='panic_sell_all_deals',
action_id=str(bot_id)
)
print(f'Panic Close - {pair}')
time.sleep(5)
return deal_close
def get_positions():
open_positions = {}
all_positions = ftx.fetchPositions(None, {"showAvgPrice": True})
if 'info' in all_positions[0]:
for y in all_positions:
x = y['info']
future = (x["future"])
size = (x["size"])
side = (x["side"])
cost = (x["cost"])
recentAverageOpenPrice = (x["recentAverageOpenPrice"])
if size != '0.0':
open_positions[future] = size, side, cost, recentAverageOpenPrice
else:
for x in all_positions:
future = (x["future"])
size = (x["size"])
side = (x["side"])
cost = (x["cost"])
recentAverageOpenPrice = (x["recentAverageOpenPrice"])
if size != '0.0':
open_positions[future] = size, side, cost, recentAverageOpenPrice
def load_bot_ids(filename):
d = {}
with open(filename) as f:
for line in f:
(key, val) = line.split(':')
d[key] = val.rstrip('\n')
return d
def get_max_bot_usage(balance):
if config.MARTINGALE_VOLUME_COEFFICIENT == 1.0:
max_bot_usage = (config.BASE_ORDER_VOLUME + (
config.SAFETY_ORDER_VOLUME * config.MAX_SAFETY_ORDERS)) / config.LEVERAGE_CUSTOM_VALUE
else:
max_bot_usage = (config.BASE_ORDER_VOLUME + (config.SAFETY_ORDER_VOLUME * (
config.MARTINGALE_VOLUME_COEFFICIENT ** config.MAX_SAFETY_ORDERS - 1) / (
config.MARTINGALE_VOLUME_COEFFICIENT - 1))) / config.LEVERAGE_CUSTOM_VALUE
return max_bot_usage
def disable_bot(pair, bot_id):
f = open("3ctrigger_log.txt", "a")
f.write(f'Disable bot for {pair} - {bot_id} at {strftime("%Y-%m-%d %H:%M:%S", gmtime())} UTC\n')
f.close()
error, data = p3cw.request(
entity='bots',
action='disable',
action_id=str(bot_id),
)
print(f'Error: {error}')
print(f'Bot Disabled for {pair} - {bot_id}')
def get_bot_info():
data = []
bot_info = []
first_run = True
base_offset = 100
offset = 0
while len(data) == 100 or first_run:
first_run = False
error, data = p3cw.request(
entity='bots',
action='',
payload={
"account_id": config.TC_ACCOUNT_ID,
"limit": base_offset,
"offset": offset,
}
)
if type(data) is not list:
print("Data from 3Commas is not a list.")
print(data)
data = []
bot_info = bot_info + data
offset += base_offset
return bot_info
def get_enabled_bots():
enabled_bots = {}
bot_list = get_bot_info()
for bot in bot_list:
if bot["is_enabled"] == True:
bot_id = bot["id"]
bot_pair = bot["pairs"][0]
bot_strategy = bot["strategy"]
enabled_bots[bot_pair[4:]] = bot_id, bot_strategy
return enabled_bots
def perp_stats(perp):
stats = []
time_frame_mins = config.TF
htf_mins = time_frame_mins * config.HTF_MULTIPLIER
adx_length = config.ADX_LENGTH
ema_length = config.EMA_LENGTH
htf_fast_ema = config.HTF_FAST_EMA
htf_slow_ema = config.HTF_SLOW_EMA
look_back = max(adx_length, ema_length) * 4
htf_look_back = htf_slow_ema * 4
current_time = datetime.datetime.now()
from_time = current_time - datetime.timedelta(minutes=time_frame_mins * look_back)
htf_from_time = current_time - datetime.timedelta(minutes=htf_mins * htf_look_back)
from_time_stamp = int(from_time.timestamp() * 1000)
htf_from_time_stamp = int(htf_from_time.timestamp() * 1000)
if time_frame_mins < 60:
time_frame = time_frame_mins
time_frame_units = 'm'
elif time_frame_mins >= 60:
time_frame = int(time_frame_mins // 60)
time_frame_units = 'h'
open_positions = {}
unsorted_tradable_perps = []
sorted_tradable_perps = []
tradable_perps = {}
enabled_bots = {}
Check for existing list of bot id's and load into a dictionary
longbots_file = Path("lbotid_list.txt")
shortbots_file = Path("sbotid_list.txt")
if not longbots_file.is_file() or not shortbots_file.is_file():
print("No bot ID lists were found. Create bots and ID list before continuing.")
print("Bye!")
sys.exit()
load files into a dictionary
long_bot_ids = {}
short_bot_ids = {}
long_bot_ids = load_bot_ids("lbotid_list.txt")
short_bot_ids = load_bot_ids("sbotid_list.txt")
Check perp lists for mismatches? Or just assume they are the same - or run it at bot creation?
tradeable_balance = get_tradeable_balance()
bot_usage = get_max_bot_usage(tradeable_balance)
print(f'Max bot usage: {bot_usage}')
Calc max number of bots - constrained by bot usage
if math.floor((float(tradeable_balance) * config.FUNDS_USAGE) / bot_usage) < config.MAX_OPEN_POSITIONS:
max_positions = math.floor((float(tradeable_balance) * config.FUNDS_USAGE) / bot_usage)
else:
max_positions = config.MAX_OPEN_POSITIONS
print(f'Max positions: {max_positions}')
last_balance_check = strftime("%Y-%m-%d", gmtime())
f = open("3ctrigger_log.txt", "a")
f.write("<<<<>>>>\n")
f.write(f'Script Run at {strftime("%Y-%m-%d %H:%M:%S", gmtime())} UTC\n')
f.write(f'Time-frame: {config.TF}\n')
f.write(f'Balance: {tradeable_balance}, Max Positions: {max_positions}\n')
f.write("<<<<>>>>\n")
f.close()
update_stats_time = True
<<<<<<<<<<< START LOOP HERE >>>>>>>>>>>>>>>>>
while True:
time.sleep(0.5) # Give the CPU a break.
while update_stats_time:
print('Getting perps OHLCV data...')
for perp in long_bot_ids:
print(".", end=" ")
unfiltered_stats, trend_direction = perp_stats(perp)
ADX = unfiltered_stats[1]
ADX_Slope = unfiltered_stats[2]
DM_plus = unfiltered_stats[3]
DM_minus = unfiltered_stats[4]
RSI = unfiltered_stats[6]
if ADX > 25 and (ADX_Slope > 0 and ((DM_plus > DM_minus and ADX > DM_minus) or (
ADX < DM_plus and ADX < DM_minus))) and DM_plus > DM_minus and RSI < 50 and trend_direction == "up":
unfiltered_stats.append("long")
unsorted_tradable_perps.append(unfiltered_stats)
elif ADX > 25 and (ADX_Slope > 0 and ((DM_plus < DM_minus and ADX > DM_plus) or (
ADX < DM_plus and ADX < DM_minus))) and DM_plus < DM_minus and RSI > 50 and trend_direction == "down":
unfiltered_stats.append("short")
unsorted_tradable_perps.append(unfiltered_stats)
elif ADX_Slope < 0:
unfiltered_stats.append("disable")
unsorted_tradable_perps.append(unfiltered_stats)
else:
unfiltered_stats.append("ignore")
unsorted_tradable_perps.append(unfiltered_stats)
`