Compare commits

..

No commits in common. "master" and "release-v0.5" have entirely different histories.

24 changed files with 288 additions and 669 deletions

View File

@ -1,10 +1,43 @@
FROM dockerproxy.com/veejar/python-ta-lib FROM veejar/python-ta-lib
ENV PYTHONIOENCODING=utf-8 ENV PYTHONIOENCODING=utf-8
ENV TZ Asia/Shanghai ENV TIME_ZONE Asia/Shanghai
# # 更新apt-get源
# RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \
# echo > /etc/apt/sources.list && \
# cat /etc/apt/sources.list && \
# echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian/ buster main contrib non-free" >/etc/apt/sources.list && \
# echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian/ buster-updates main contrib non-free" >>/etc/apt/sources.list && \
# echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian/ buster-backports main contrib non-free" >>/etc/apt/sources.list && \
# echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian-security buster/updates main contrib non-free" >>/etc/apt/sources.list
# RUN apt-get update && apt-get upgrade -y
# ENV APT_PKG_TEMPORARY="build-essential autoconf automake autotools-dev libopenblas-dev python3-dev"
# ENV APT_PKG="python3 python3-pip python3-scipy python3-numpy python3-pandas python-is-python3"
# ENV PYPI_PKG="TA-Lib numpy pandas"
# ENV DEBIAN_FRONTEND=noninteractive
# COPY ta-lib ./ta-lib
# RUN apt-get update && apt-get upgrade -y && \
# apt-get install -y ${APT_PKG_TEMPORARY} ${APT_PKG} && \
# ln -s /usr/include/locale.h /usr/include/xlocale.h && \
# # compile TA-Lib library
# cd ta-lib && \
# ./configure --prefix=/usr; \
# make && \
# make install && \
# cd .. && \
# rm -rf ta-lib && \
# \
# pip3 install --no-cache-dir $PYPI_PKG && \
# apt-get autoremove -y ${APT_PKG_TEMPORARY} && \
# rm -rf /var/lib/apt/lists/*
RUN pip3 install -i https://mirrors.aliyun.com/pypi/simple/ binance binance_connector numpy requests schedule TA_Lib
# RUN pip3 install -i https://mirrors.aliyun.com/pypi/simple/ binance binance_connector requests schedule
WORKDIR /opt/ WORKDIR /opt/
COPY ["./", "/opt/"] COPY ["./", "/opt/"]
RUN pip3 install -i https://mirrors.aliyun.com/pypi/simple/ -r requirements.txt
CMD python3 -u main.py CMD python3 -u main.py

19
bn.py Normal file
View File

@ -0,0 +1,19 @@
from binance.spot import Spot
client = Spot()
# Get klines
def klines(symbol, interval):
lines = client.klines(symbol,interval)
return lines
# Get Symbols
def symbols():
info = client.exchange_info()
symbols = []
for s in info['symbols']:
if s['symbol'].endswith('USDT'):
symbols.append(s['symbol'])
return symbols

View File

@ -1,106 +0,0 @@
import requests
from binance.spot import Spot
import pandas as pd
from binance.um_futures import UMFutures
import urllib3
api_key = "HCpeel8g6fsTK2630b7BvGBcS09Z3qfXkLVcAY2JkpaiMm1J6DWRvoQZBQlElDJg"
api_secret= "TySs6onlHOTrGzV8fMdDxLKTWWYnQ4rCHVAmjrcHby17acKflmo7xVTWVsbqtxe7"
client = Spot(api_key, api_secret)
future_client = UMFutures(api_key, api_secret)
# 获取市值前top的币种
def _get_top_coins_by_market_cap(top):
coingecko_url = "https://api.coingecko.com/api/v3/coins/markets"
params = {
'vs_currency': 'usd',
'order': 'market_cap_desc',
'per_page': top,
'page': 1
}
urllib3.disable_warnings(category=urllib3.exceptions.InsecureRequestWarning)
response = requests.get(coingecko_url, params=params, verify=False)
coins = response.json()
return coins
# 获取Binance上的USDT交易对信息
def _get_binance_usdt_pairs():
url = "https://api.binance.com/api/v3/exchangeInfo"
urllib3.disable_warnings(category=urllib3.exceptions.InsecureRequestWarning)
response = requests.get(url, verify=False)
data = response.json()
usdt_pairs = [symbol['symbol'] for symbol in data['symbols'] if (symbol['quoteAsset'] == 'USDT' and symbol['status'] == 'TRADING')]
return usdt_pairs
def get_top_binance_usdt_pairs(top):
# 获取市值前10的币种
top_coins = _get_top_coins_by_market_cap(top)
# 获取Binance上的USDT交易对
usdt_pairs = _get_binance_usdt_pairs()
# 筛选出前10币种中与USDT有交易对的币种
top_pairs = []
for coin in top_coins:
coin_symbol = coin['symbol'].upper()
pair = f"{coin_symbol}USDT"
if pair in usdt_pairs:
top_pairs.append(pair)
return top_pairs
## 获取所有现货交易对
def get_symbols():
data = client.exchange_info()["symbols"]
# 创建DataFrame
columns = ['symbol', 'status', 'baseAsset', 'quoteAsset']
df = pd.DataFrame(data, columns=columns)
df = df[(df['status'] == 'TRADING') & (df['quoteAsset'] == 'USDT')]
return df['symbol']
def get_future_symbols():
data = future_client.exchange_info()["symbols"]
# 创建DataFrame
columns = ['symbol', 'status','contractType', 'baseAsset', 'quoteAsset']
df = pd.DataFrame(data, columns=columns)
# 过滤出交易对
df = df[(df['status'] == 'TRADING') & (df['contractType'] == 'PERPETUAL')]
return df['symbol']
## 根据交易对和周期获取数据集
def get_klines(symbol,interval, future = False,limit=1000):
# 获取 k 线数据
data = {}
if future == True:
data = future_client.klines(symbol, interval, limit=limit)
else:
data = client.klines(symbol, interval,limit=limit)
# 将数据转换为DataFrame
columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume',
'close_time', 'quote_asset_volume', 'number_of_trades',
'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore']
df = pd.DataFrame(data, columns=columns)
# 转化成 float
df['open'] = df['open'].astype('float64')
df['high'] = df['high'].astype('float64')
df['low'] = df['low'].astype('float64')
df['close'] = df['close'].astype('float64')
df['volume'] = df['volume'].astype('float64')
# 将时间戳转换为日期时间格式
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms', utc=True).map(lambda x: x.tz_convert('Asia/Shanghai'))
df['close_time'] = pd.to_datetime(df['close_time'], unit='ms', utc=True).map(lambda x: x.tz_convert('Asia/Shanghai'))
return df

View File

@ -1,19 +0,0 @@
import requests
import setting
import urllib3
url = 'https://oapi.dingtalk.com/robot/send?access_token=2278b723cd363bb6f85592c743b59b166e70b9e02a275bb5cedbc33b53a5cbdc'
# 发送消息
def send_message(text, isAtAll = False):
formData = {
"msgtype": "text",
"text": {
"content": text
},
"at": {
"isAtAll": isAtAll
}
}
urllib3.disable_warnings(category=urllib3.exceptions.InsecureRequestWarning)
print(requests.post(url, json=formData, verify=False).json())

View File

@ -1,10 +0,0 @@
from discord_webhook import DiscordWebhook, DiscordEmbed
def send_message(url,title,content):
webhook = DiscordWebhook(url)
embed = DiscordEmbed(title=title, description=content, color="03b2f8")
webhook.add_embed(embed)
response = webhook.execute()

62
main.py
View File

@ -1,58 +1,32 @@
import schedule import schedule
import bn
import settings
import time import time
import dingding import strategy.crossover as crossover
import monitors.jin10_cal as jin10 import strategy.large_trans as lt
from monitors import macd_boll,vol_up # 获取交易所交易对
# from plombery import task, get_logger, Trigger, register_pipeline symbols = bn.symbols()
#vegas for s in symbols:
# schedule.every().hour.at(":00").do(vegas.run_crypto, interval = '1h') # 5m
# times = ["00:00", "04:00", "08:00", "12:00", "16:00", "20:00"] schedule.every(settings.whaleAlert_minutes).minutes.do(lt.strategy_run)
# for t in times:
# schedule.every().day.at(t).do(vegas.run_crypto, interval = '4h')
#vegas_cross
# schedule.every().hour.at(":00").do(vegas_cross.run_crypto, interval = '1h')
# times = ["00:00", "04:00", "08:00", "12:00", "16:00", "20:00"]
# for t in times:
# schedule.every().day.at(t).do(vegas_cross.run_crypto, interval = '4h')
# register_pipeline(tasks=[vol_up.run_crypto('15')], triggers=[Trigger()]) # 5m
# schedule.every(5).minutes.do(crossover.strategy_run, symbol=s, interval='5m')
# 30m
# schedule.every(30).minutes.do(crossover.strategy_run, symbol=s, interval='30m')
# 1h
# schedule.every(1).hours.do(crossover.strategy_run, symbol=s, interval='1h')
#vol # 4h
schedule.every(5).minutes.do(vol_up.run_crypto, interval = '5m') # schedule.every(4).hours.do(crossover.strategy_run, symbol=s, interval='4h')
schedule.every().hour.at(":00").do(vol_up.run_crypto, interval = '15m') print(f'监控开始... ChatID: {settings.chat_id}')
schedule.every().hour.at(":15").do(vol_up.run_crypto, interval = '15m')
schedule.every().hour.at(":30").do(vol_up.run_crypto, interval = '15m')
schedule.every().hour.at(":45").do(vol_up.run_crypto, interval = '15m')
schedule.every().hour.at(":00").do(vol_up.run_crypto, interval = '1h')
#macd_boll
schedule.every().hour.at(":00").do(macd_boll.run_crypto, interval = '15m')
schedule.every().hour.at(":15").do(macd_boll.run_crypto, interval = '15m')
schedule.every().hour.at(":30").do(macd_boll.run_crypto, interval = '15m')
schedule.every().hour.at(":45").do(macd_boll.run_crypto, interval = '15m')
schedule.every().hour.at(":00").do(macd_boll.run_crypto, interval = '1h')
times = ["00:00", "04:00", "08:00", "12:00", "16:00", "20:00"]
for t in times:
schedule.every().day.at(t).do(macd_boll.run_crypto, interval = '4h')
#jin10
schedule.every().day.at("09:00").do(jin10.run)
version = 'V1.4'
text = f'☕️ Signals running... {version} !'
print(text)
dingding.send_message(text)
while True: while True:
schedule.run_pending() schedule.run_pending()
time.sleep(1) time.sleep(1)

View File

@ -1,72 +0,0 @@
import requests
import datetime
import time
import discord_sender,dingding
def run():
print('金 10 数据数据日历数据抓取...')
addtion_day = 1
items = []
while(addtion_day <= 7):
data_day = datetime.datetime.now() + datetime.timedelta(days=addtion_day)
addtion_day = addtion_day + 1
result = _get_jin10_cal_by_day(data_day.year, data_day.month, data_day.day)
items.extend(result)
time.sleep(1)
if len(items) > 0:
content = ""
for item in items:
print(item)
content += _build_content(item)
print(content)
dingding.send_message(content)
url = 'https://discord.com/api/webhooks/1287027684370681939/fzinKKoNK6KXoLNdj1wttSDtIGio-VHijaYzZInoajHHu-PZyZXVpWDxM6_XrxCtPrPY'
discord_sender.send_message(url, '【最近重要数据公布时间】',content)
def _build_content(item):
content = f"{item['name']} {item['country']} {item['time_period']}\r\n"
if item['previous'] != None:
content += f"前值: {item['previous']}\r\n"
if item['consensus'] != None:
content += f"预测值: {item['consensus']}\r\n"
content += f"重要星级:"
for s in range(item['star']):
content+=""
pub_date = datetime.datetime.strptime(item['pub_time'],'%Y-%m-%dT%H:%M:%S.%fZ') + datetime.timedelta(hours=8)
content += f"\r\n公布时间: {pub_date.strftime('%Y-%m-%d %H:%M:%S')}\r\n\r\n"
return content
def _fill_number(number):
if number<10:
return "0" + str(number)
return number
def _get_jin10_cal_by_day(year,month, day):
url = f"https://cdn-rili.jin10.com/data/{year}/{_fill_number(month)}{_fill_number(day)}/economics.json"
print(url)
data = requests.get(url).json()
items = []
for item in data:
if item['star'] >= 4:
items.append(item)
return items

View File

@ -1,79 +0,0 @@
import talib
import numpy as np
import time,setting
import telegram_sender
from datasource import crypto
import dingding
import discord_sender
# crossover 函数:检测上穿信号
def crossover(series1, series2):
return (series1 > series2) & (series1.shift(1) <= series2.shift(1))
# crossunder 函数:检测下穿信号
def crossunder(series1, series2):
return (series1 < series2) & (series1.shift(1) >= series2.shift(1))
## 检查信号
def stratergy_run(symbol, interval, df, debug):
macd_fast_length = 12
macd_slow_length = 26
macd_signal_length = 9
bollinger_length = 20
bollinger_mult = 2.0
# 计算EMA 144 200
fast_ema = talib.EMA(df['close'], timeperiod=144)
slow_ema = talib.EMA(df['close'], timeperiod=200)
# 计算 MACD
macd, macd_signal, macd_hist = talib.MACD(df['close'], fastperiod=macd_fast_length, slowperiod=macd_slow_length, signalperiod=macd_signal_length)
# 计算布林带
upperband, middleband, lowerband = talib.BBANDS(df['close'], timeperiod=bollinger_length, nbdevup=bollinger_mult, nbdevdn=bollinger_mult, matype=0)
# 生成交易信号
long_condition = (macd.shift(1) <= 0) & (macd > 0) & (df['high'] < upperband) & ((df['close'] > fast_ema) | (df['close'] > slow_ema))
short_condition = (macd.shift(1) >= 0) & (macd < 0) & (df['low'] > lowerband) & ((df['close'] < fast_ema) | (df['close'] < slow_ema))
df['Long_Signal'] = np.where(long_condition, True, False)
df['Short_Signal'] = np.where(short_condition,True, False)
latest = df.iloc[-2]
print(f"{symbol} - {interval}】 is checked!")
direction = ""
if latest['Short_Signal'] == True:
direction = ''
if latest['Long_Signal'] == True:
direction = ''
if direction != "":
message = '🦄Signals Notificaiton🦄\r\n\r\n'
message += f"策略:【MACD+BOLL策略V1.1】\r\n"
message += f"品种: {symbol}\r\n"
message += f"周期: {interval}\r\n"
message += f"信号: 【{direction}\r\n"
message += f"收盘价: {latest['close']}\r\n"
if debug == False:
# url = 'https://discordapp.com/api/webhooks/1286585288986198048/iQ-yr26ViW45GM48ql8rPu70Iumqcmn_XXAmxAcKGeiQBmTQoDPeq-TmlChvIHkw_HJ-'
# discord_sender.send_message(url,'🦄信号提醒🦄',message)
dingding.send_message(message)
print(f"{symbol} - {interval}】 is singal fired!")
else:
print(message)
def run_crypto(interval, debug=False):
print('MACD+BOLL is running...')
time.sleep(5)
for s in setting.symbols:
df = crypto.get_klines(s, interval, True)
stratergy_run(s,interval, df, debug)
time.sleep(1)

View File

@ -1,63 +0,0 @@
import talib
import time,setting
import telegram_sender
from datasource import crypto
import dingding
import discord_sender
import setting
# crossover 函数:检测上穿信号
def crossover(series1, series2):
return (series1 > series2) and (series1.shift(1) <= series2.shift(1))
# crossunder 函数:检测下穿信号
def crossunder(series1, series2):
return (series1 < series2) and (series1.shift(1) >= series2.shift(1))
## 检查信号
def stratergy_run(symbol, interval, df, debug):
maxDifference = 0.005
## 计算 ema
df['ema5'] = talib.EMA(df['close'], timeperiod=5)
df['ema10'] = talib.EMA(df['close'], timeperiod=10)
df['ema30'] = talib.EMA(df['close'], timeperiod=30)
df['ema144'] = talib.EMA(df['close'], timeperiod=144)
df['shortDiff'] = abs(df['ema5'] - df['ema10']) / df['ema10']
df['midDiff'] = abs(df['ema10'] - df['ema30']) / df['ema30']
df['longDiff'] = abs(df['ema30'] - df['ema144']) / df['ema144']
df['priceCheck'] = ((df['longDiff'] <= maxDifference) & (df['midDiff'] <= maxDifference) & (df['shortDiff'] <= maxDifference))
df['isLongArrangement'] = ((df['ema5'] > df['ema10']) & (df['ema10'] > df['ema30']) & (df['ema30'] > df['ema144']))
df['isShortArrangement'] = ((df['ema5'] < df['ema10']) & (df['ema10'] < df['ema30']) & (df['ema30'] < df['ema144']))
d1 = df.iloc[-1]
d2 = df.iloc[-2]
d3 = df.iloc[-3]
maxDiff = max(d1['shortDiff'], d1['midDiff'], d1['longDiff'])
minDiff = min(d1['shortDiff'], d1['midDiff'], d1['longDiff'])
isbullish = d1['isLongArrangement'] == True and d2['isLongArrangement'] == True and d3['isLongArrangement'] == False
isBear = d1['isShortArrangement'] == True and d2['isShortArrangement'] == True and d3['isShortArrangement'] == False
print(f"{symbol} - {interval} bullish: {isbullish} | bear : {isBear} | LongArrangement: {d1['isLongArrangement']} | ShortArrangement: {d1['isShortArrangement']}")
if(isbullish | isBear):
message = f"策略:【均线排列信号】\r\n"
message += f"品种: {symbol}\r\n"
message += f"周期: {interval}\r\n"
message += f"信号: 【{'' if isbullish else ''}\r\n"
message += f"收盘价: {d1['close']}\r\n"
url = 'https://discordapp.com/api/webhooks/1285867836454998077/JNAFUyur_ygOJIh6C4beUAVYMpm1TZf4IEeMn8Q1p0TglO1Hjyiu2LQqiU5AxVovWyiO'
discord_sender.send_message(url,'🦄信号提醒🦄',message)
def run_crypto(interval, debug=False):
for s in setting.symbols:
df = crypto.get_klines(s, interval)
stratergy_run(s,interval, df, debug)
time.sleep(1)

View File

@ -1,73 +0,0 @@
import talib
import numpy as np
import time,setting
import telegram_sender
from datasource import crypto
import dingding
import discord_sender
# crossover 函数:检测上穿信号
def crossover(series1, series2):
return (series1 > series2) & (series1.shift(1) <= series2.shift(1))
# crossunder 函数:检测下穿信号
def crossunder(series1, series2):
return (series1 < series2) & (series1.shift(1) >= series2.shift(1))
## 检查信号
def stratergy_run(symbol, interval, df, debug):
## 计算 ema
df['ema13'] = talib.EMA(df['close'], timeperiod=13)
df['ema144'] = talib.EMA(df['close'], timeperiod=144)
df['ema169'] = talib.EMA(df['close'], timeperiod=169)
df['ema576'] = talib.EMA(df['close'], timeperiod=576)
df['ema676'] = talib.EMA(df['close'], timeperiod=676)
maxline = np.maximum(df['ema144'], df['ema169'])
minline = np.minimum(df['ema144'], df['ema169'])
shortArragement = df['ema13'] < minline
longArrangement = df['ema13'] > maxline
confuse = (df['ema13'] >= minline) & (df['ema13'] <= maxline)
crossRatio = 0.2
shortA = crossunder(df['ema13'], minline)
shortB = shortArragement & crossunder(df['close'], minline) & (((minline - df['close']) / df.apply(lambda x: abs(x['open'] - x['close']), axis=1)) > crossRatio)
df['shortResut'] = (shortA | shortB) & (confuse == False)
longA = crossover(df['ema13'], maxline)
longB = longArrangement & crossover(df['close'], maxline) & (((df['close'] - maxline) / df.apply(lambda x: abs(x['open'] - x['close']), axis=1)) > crossRatio)
df['longResut'] = (longA | longB) & (confuse == False)
latest = df.iloc[-1]
direction = ""
if latest['shortResut']==True:
direction = ''
if latest['longResut']==True:
direction = ''
message = f"策略:【Vegas反转策略】\r\n"
message += f"品种: {symbol}\r\n"
message += f"周期: {interval}\r\n"
message += f"信号: 【{direction}\r\n"
message += f"收盘价: {latest['close']}\r\n"
print(f"{symbol} - {interval}】 is checked!")
if direction != "":
if debug == False:
url = 'https://discordapp.com/api/webhooks/1285867836454998077/JNAFUyur_ygOJIh6C4beUAVYMpm1TZf4IEeMn8Q1p0TglO1Hjyiu2LQqiU5AxVovWyiO'
discord_sender.send_message(url,'🦄信号提醒🦄',message)
print(f"{symbol} - {interval}】 is singal fired!")
else:
print(message)
def run_crypto(interval, debug=False):
for s in setting.symbols:
df = crypto.get_klines(s, interval)
stratergy_run(s,interval, df, debug)
time.sleep(1)

View File

@ -1,65 +0,0 @@
import talib
import numpy as np
import time,setting
import telegram_sender
from datasource import crypto
import dingding
import discord_sender
import setting
# crossover 函数:检测上穿信号
def crossover(series1, series2):
return (series1 > series2) & (series1.shift(1) <= series2.shift(1))
# crossunder 函数:检测下穿信号
def crossunder(series1, series2):
return (series1 < series2) & (series1.shift(1) >= series2.shift(1))
## 检查信号
def stratergy_run(symbol, interval, df, debug):
## 计算 ema
df['ema144'] = talib.EMA(df['close'], timeperiod=144)
df['ema169'] = talib.EMA(df['close'], timeperiod=169)
df['ema576'] = talib.EMA(df['close'], timeperiod=576)
df['ema676'] = talib.EMA(df['close'], timeperiod=676)
max_low_line = np.maximum(df['ema144'], df['ema169'])
min_low_line = np.minimum(df['ema144'], df['ema169'])
max_high_line = np.maximum(df['ema576'], df['ema676'])
min_high_line = np.minimum(df['ema576'], df['ema676'])
df['longSignal'] = crossover(min_low_line, max_high_line)
df['shortSignal'] = crossunder(max_low_line, min_high_line)
latest = df.iloc[-1]
direction = ""
if latest['shortSignal']==True:
direction = ''
if latest['longSignal']==True:
direction = ''
message = f"策略:【Vegas金叉死叉策略】\r\n"
message += f"品种: {symbol}\r\n"
message += f"周期: {interval}\r\n"
message += f"信号: 【{direction}\r\n"
message += f"收盘价: {latest['close']}\r\n"
print(f"{symbol} - {interval}】 is checked!")
if direction != "":
if debug == False:
url = 'https://discordapp.com/api/webhooks/1285867836454998077/JNAFUyur_ygOJIh6C4beUAVYMpm1TZf4IEeMn8Q1p0TglO1Hjyiu2LQqiU5AxVovWyiO'
discord_sender.send_message(url,'🦄信号提醒🦄',message)
print(f"{symbol} - {interval}】 is singal fired!")
else:
print(message)
def run_crypto(interval, debug=False):
for s in setting.symbols:
df = crypto.get_klines(s, interval,True)
stratergy_run(s,interval, df, debug)
time.sleep(1)

View File

@ -1,37 +0,0 @@
# 突然放量策略
import numpy as np
from datasource import crypto
import time, dingding
def stratergy_run(symbol, interval, df, debug):
# 计算过去 30 根 K 线的平均交易量
average_volume = df["volume"].iloc[-31:-1].mean() # 倒数第 31 到倒数第 2 根的平均
# 获取当前(最后一根,即第 500 根)交易量
current_volume = df["volume"].iloc[-1]
timestamp = df['timestamp'].iloc[-1]
rate = current_volume / average_volume
rate_limit = 10
if rate > rate_limit:
message = "📢Signals Notificaiton📢\r\n\r\n"
message += f"{symbol}{interval} 出现放量 {round(rate, 2)}\r\n\r\n"
message += f"{timestamp}"
if debug == False:
dingding.send_message(message)
print(f"{symbol} - {interval}】 is singal fired!")
else:
print(message)
def run_crypto(interval, debug=False):
print(f"Vols-up strategy {interval} is running...")
symbols = crypto.get_future_symbols()
for s in symbols:
df = crypto.get_klines(s, interval, True,limit=50)
stratergy_run(s,interval, df, debug)
time.sleep(1)

View File

@ -1,10 +1,6 @@
binance binance==0.3
binance_connector binance_connector==3.1.0
binance-futures-connector numpy==1.23.4
numpy==1.26.4 requests==2.28.1
pandas schedule==1.1.0
requests TA_Lib==0.4.26
schedule
tweepy
discord_webhook
redis

View File

@ -1,14 +0,0 @@
import os
# telegram bot key
telegram_bot_key='5863718864:AAFijN65_SbbGQ0WDBggzKJw2SIcZVTVrPw'
#
chat_id = os.getenv("TQ_CHAT_ID", "@cyber4trading")
symbols = ['BTCUSDT',"ETHUSDT",'LTCUSDT','DOGEUSDT','FTMUSDT','FILUSDT','OPUSDT','SOLUSDT','BNBUSDT','BCHUSDT','ETCUSDT','ARUSDT',"REEFUSDT","BONDUSDT","VIDTUSDT","UNFIUSDT","PEOPLEUSDT","ORDIUSDT"]
#dingding bot
singal_bot_url = 'https://oapi.dingtalk.com/robot/send?access_token=2278b723cd363bb6f85592c743b59b166e70b9e02a275bb5cedbc33b53a5cbdc'

21
settings.py Normal file
View File

@ -0,0 +1,21 @@
import os
# telegram bot key
telegram_bot_key='5863718864:AAFijN65_SbbGQ0WDBggzKJw2SIcZVTVrPw'
#
chat_id = os.getenv("TQ_CHAT_ID", "@cyber4trading")
#oklink
oklink_host = 'https://www.oklink.com'
oklink_apikey='ca822b3f-2e1e-479c-8649-c1f9b62a740d'
oklink_api_headers = {
'Ok-Access-Key' : oklink_apikey
}
#whaleAlert
whaleAlert_minutes=2
whaleAlert_apikey='gPkElMPR8Hpe5LxjKisR4YSFzxRxMLj6'
whaleAlert_max_limit = os.getenv('TQ_WHALEALERT_MAX_USD_AMOUNT',1000 * 10000)

View File

@ -1,5 +0,0 @@
import datetime
def signal_text(symbol, interval, signal_type ,signal):
return f'📶信号预警📶\r\n\r\n品种:【${symbol}\r\n周期:{interval}\r\n信号类型:{signal_type}\r\n信号:{signal}\r\n\r\n{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}'

59
strategy/crossover.py Normal file
View File

@ -0,0 +1,59 @@
import talib
import numpy as np
import bn
import tg
import settings
# 检查是否出现多头排列信号
def check_bullish_crossover(data):
# 提取收盘价
close_prices = np.array([float(entry[4]) for entry in data])
# 计算移动平均线
ema7 = talib.EMA(close_prices, timeperiod=7)
ema30 = talib.EMA(close_prices, timeperiod=30)
ema100 = talib.EMA(close_prices, timeperiod=100)
ema200 = talib.EMA(close_prices, timeperiod=200)
# 判断是否出现多头排列信号
# if ema7[-1] > ema30[-1] > ema100[-1] > ema200[-1] and ema7[-2] <= ema30[-2] <= ema100[-2] <= ema200[-2]:
if ema7[-1] > ema30[-1] > ema100[-1] and ema7[-2] <= ema30[-2] <= ema100[-2]:
return True
else:
return False
# 检查是否出现空头排列信号
def check_bearish_crossover(data):
# 提取收盘价
close_prices = np.array([float(entry[4]) for entry in data])
# 计算移动平均线
ema7 = talib.EMA(close_prices, timeperiod=7)
ema30 = talib.EMA(close_prices, timeperiod=30)
ema100 = talib.EMA(close_prices, timeperiod=100)
ema200 = talib.EMA(close_prices, timeperiod=200)
# 判断是否出现空头排列信号
if ema7[-1] < ema30[-1] < ema100[-1] < ema200[-1] >= ema30[-2] >= ema100[-2]:
# if ema7[-1] < ema30[-1] < ema100[-1] < ema200[-1] and ema7[-2] >= ema30[-2] >= ema100[-2] >= ema200[-2]:
return True
else:
return False
def strategy_run(symbol, interval):
# 获取kline数据
data = bn.klines(symbol, interval)
if check_bullish_crossover(data):
print('多头排列信号出现!')
text = f'${symbol} - {interval}\r\n\r\n出现【多头排列】信号'
tg.send_message(settings.chat_id, text)
if check_bearish_crossover(data):
print("空头排列信号出现!")
text = f'${symbol} - {interval}\r\n\r\n出现【空头排列】信号'
tg.send_message(settings.chat_id, text)

34
strategy/large_trans.py Normal file
View File

@ -0,0 +1,34 @@
import requests
import settings
from datetime import datetime, timedelta
import time
import tg
import traceback
import logging
def strategy_run():
# 获取上一分钟的timestamp
last_min = datetime.now() - timedelta(minutes=settings.whaleAlert_minutes)
ts = time.mktime(last_min.timetuple())
url = f'https://api.whale-alert.io/v1/transactions?api_key={settings.whaleAlert_apikey}&start={int(ts)}'
resp = requests.get(url).json()
print(resp)
try:
if 'transactions' in resp:
data = resp['transactions']
for ts in data:
usd = int(ts['amount_usd'])
if ts['to']['owner_type'] == 'exchange' and usd > settings.whaleAlert_max_limit:
from_text = 'unknown wallet'
content = f"🚨 {ts['amount']} #{ts['symbol']} ({ts['amount_usd']} USD) 从 {from_text} 转入 #{ts['to']['owner']}"
print(content)
tg.send_message(settings.chat_id, content)
except Exception as e:
logging.error(traceback.format_exc())
tg.send_message(settings.chat_id, traceback.format_exc())

View File

@ -0,0 +1,44 @@
import talib
import numpy as np
import bn
import tg
import settings
# 获取K线价格数据
def get_prices(data):
# 提取最高价、最低价和收盘价
high_prices = [float(entry[2]) for entry in data]
low_prices = [float(entry[3]) for entry in data]
close_prices = [float(entry[4]) for entry in data]
return np.array(high_prices), np.array(low_prices), np.array(close_prices)
# 计算支撑位和压力位
def calculate_support_resistance(data):
# 获取价格数据
high_prices, low_prices, close_prices = get_prices(data)
# 计算平均真实范围ATR
atr = talib.ATR(high_prices, low_prices, close_prices, timeperiod=14)
# 计算支撑位和压力位
support = talib.SMA(close_prices - 1.618 * atr, timeperiod=20)
resistance = talib.SMA(close_prices + 1.618 * atr, timeperiod=20)
return support, resistance
def strategy_run(symbol, interval):
# 获取kline数据
data = bn.klines(symbol, interval)
support_levels, resistance_levels = calculate_support_resistance(data)
# 打印支撑位和压力位
print("支撑位:", support_levels)
print("压力位:", resistance_levels)
# if check_bullish_crossover(data):
# print('多头排列信号出现!')
# text = f'${symbol} - {interval}\r\n\r\n出现【多头排列】信号'
# tg.send_message(settings.chat_id, text)

9
strategy_test.py Normal file
View File

@ -0,0 +1,9 @@
import strategy.support_resistance as sr
import strategy.large_trans as lt
lt.strategy_run()
# sr.strategy_run('BTCUSDT', '1h')

View File

@ -1,6 +0,0 @@
import sys
from monitors import vol_up
if __name__ == "__main__":
args = sys.argv
vol_up.run_crypto(args[1])

View File

@ -1,13 +0,0 @@
import requests
import setting
import urllib3
# 发送消息
def send_message(chat_id, text):
url = f'https://api.telegram.org/bot{setting.telegram_bot_key}/sendMessage'
formData = {
"chat_id" : chat_id,
"text" : text
}
urllib3.disable_warnings(category=urllib3.exceptions.InsecureRequestWarning)
requests.post(url, data= formData, verify=False)

75
test.py
View File

@ -1,54 +1,35 @@
import requests import bn
import datasource.crypto import pandas as pd
from monitors import move import mplfinance as mpf
from datasource import crypto import datetime as dt
import talib import strategy.large_trans as lt
import discord_sender
from monitors import vegas_cross, jin10_cal,vol_up # def binanceDataFrame(klines):
from datasource import crypto # df = pd.DataFrame(klines.reshape(-1,12),dtype=float, columns = ('Open Time',
from monitors import macd_boll # 'Open',
import datasource # 'High',
from binance.um_futures import UMFutures # 'Low',
import redis,dingding # 'Close',
# 'Volume',
# 'Close time',
# 'Quote asset volume',
# 'Number of trades',
# 'Taker buy base asset volume',
# 'Taker buy quote asset volume',
# 'Ignore'))
# df['Open Time'] = pd.to_datetime(df['Open Time'], unit='ms')
# vol_up.run_crypto('1h') # return df
# r = redis.Redis(host='45.76.104.85', port=6379, db=0 ,password="redis_ihkXTj") # klines = bn.klines('BTCUSDT', '1h')
# r.set('r_symbols', "test")
# print(r.get('r_symbols')) # df = pd.DataFrame(klines,dtype=float)
# df.columns = ['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'ctime', 'Quote asset volume', 'Number of trades', 'Taker buy base asset volume', 'Taker buy quote asset volume', 'Can be ignored']
print(datasource.crypto.get_future_symbols()) # df.index = [dt.datetime.fromtimestamp(x/1000.0) for x in df.ctime]
# mpf.plot(df, type='line')
# macd_boll.run_crypto('15m', debug=True)
# jin10_cal.run()
# print(crypto._get_top_coins_by_market_cap(20))
# vegas_cross.run_crypto('1h')
lt.strategy_run()
# key = 'QSZvYevTytwi8CJEkiUqqlZRQBOjIa23BoB8wFwTSY26GBAFkViTExex2mFNJ0ij'
# secret = '1eGO4aeICAxPRXQzw2lQBc0QAkIKn6WiCV4cRLnUwnJulzixYFkoBeho5ZzsKTbn'
# client = UMFutures(key=key, secret=secret)
# # print(client.exchange_info())
# # data = client.funding_rate('BTCUSD_PERP', limit=1)
# print(client.balance())
# fundingRate = float(data[0]['fundingRate']) * 100
# text = f"币种: {data[0]['symbol']}\r\n资金费率: {fundingRate} %"
# mUrl = "https://discordapp.com/api/webhooks/1285898004641091605/DwIh9yZvrU6TwelVmJr96XBdpFTEEpeFD8GsZpH7rBdwT4UwVyZTrtdmBzS4ae0Ta7PH"
# discord_sender.send_message(mUrl, '消息内容',text)
# dingding.send_message('信号 测试')

11
tg.py Normal file
View File

@ -0,0 +1,11 @@
import requests
import settings
# 发送消息
def send_message(chat_id, text):
url = f'https://api.telegram.org/bot{settings.telegram_bot_key}/sendMessage'
formData = {
"chat_id" : chat_id,
"text" : text
}
requests.post(url, data= formData)