Beispiel #1
0
def create_order(side: str, settings: dict, bot: Binance):
    """ Создание ордера на основе текущего шага стратегии"""
    return bot.futuresCreateOrder(symbol=settings['symbol'],
                                  recvWindow=15000,
                                  side=side,
                                  type='MARKET',
                                  quantity=settings['amount'])
Beispiel #2
0
from binance_api import Binance
import threading
import pdb
import time
import json
#pdb.set_trace()

bot = Binance(API_KEY='', API_SECRET='')

period_record = 20  #Сколько производить запись в секундах
delay = 5  #задержка между двумя запросми (по умолчанию)(в секундах)


def record_in_file():  #запись фильтрованных значений
    #print(range_for_record)
    for string in range_for_record:
        test_data.write(str(string))
        test_data.write(",\n")


def request_time():
    current_time = bot.time()
    current_time = int(current_time['serverTime'])
    return current_time


def countdown(end_record):  #параллельный поток для показа времени
    while 1:
        current_time = request_time()
        ostatok = (end_record - current_time) / 1000
        if current_time >= end_record:
Beispiel #3
0
def getBinanceAPI(key, secret):
    api = Binance(API_KEY=key, API_SECRET=secret)
    return api
Beispiel #4
0
import sqlite3
import logging
import os
import math

from datetime import datetime
from binance_api import Binance
from time import sleep
from threading import Thread

bot = Binance(API_KEY='API_KEY', API_SECRET='API_SECRET')

sets = [
    dict(
        symbol='BNBBTC',  # Пара для отслеживания
        strategy=
        "Short",  # Стратегия - Long (повышение), Short (понижение)           
        stop_loss_perc=0.9,  # % оставания от цены
        stop_loss_fixed=
        0,  # Изначальный stop-loss, можно установить руками нужную сумму, потом бот подтянет.
        # Можно указать 0, тогда бот высчитает, возьмет текущую цену и применит к ней процент
        amount=
        0.001  # Кол-во монет, которое планируем продать (в случае Long) или купить (в случае Short)
        # Если указываем Long, то альты для продажи (Например, продать 0.1 ETH в паре ETHBTC)
        # Если Short, то кол-во, на которое покупать, например купить на 0.1 BTC по паре ETHBTC
    )
]


class Threada(Thread):
    def __init__(self, paira):
Beispiel #5
0
from binance_api import Binance

bot = Binance(API_KEY='****', API_SECRET='****')

get_json = bot.futuresExchangeInfo()
key_sym = get_json['symbols']
symb_list = []
for i in key_sym:
    symb_list.append(i['symbol'])
# c = b[0]['symbol']\
symb_list.sort()


# список по буквам
def alphab_lists(letter):
    alph_list = []
    for i in symb_list:
        if i.startswith(letter):
            alph_list.append(i)
    return alph_list


# ticker list
def tickers_list(symb_list):
    get_json = bot.futuresExchangeInfo()
    key_sym = get_json['symbols']
    # symb_list = []
    for i in key_sym:
        symb_list.append(i['symbol'])
    symb_list.sort()
    return symb_list
from binance_api import Binance
from datetime import datetime
import json
import time

with open('API.txt')as apikeys:
    API = apikeys.read().split()

bot = Binance(API_KEY=API[0], API_SECRET=API[1])

STARTTIME = 1514754000000  # Begin from 01.01.2018 in ms
INTERVAL = 1000 * 60 * 60 * 24  # 1 day in ms
ENDTIME = datetime.now().timestamp() * 1000  # Current date in ms
cls = 4  # Closed price index from response
tcls = 6  # Closed candle index from response
TIMEFRAME = '1h'  # time frame 1 hour
TRADE_PAIR = 'BTCUSDT'  # trade pair BTC/USDT


def get_history(pair, tf, start, end, interval=86400000, cd=100):
    """
    Getting the history of the chart from Binance
    :param pair: cryptocurrency pair, a story have to get
    :param tf: time frame
    :param start: date in ms, starting point
    :param end: date in ms, end point
    :param interval: step in ms, max step 90 days, default=1 day
    :param cd: cooldown, if we don't want to get banned
    :return: dictionary with historical data, {date+time: price}
    """
    history = {}
Beispiel #7
0
    return [fProfit, fPriceBuyF, fPriceSellF, fDeal]


# исходные данные ----------------
# валютная пара
sPair = 'EOSUSDC'
# количество интервалов для анализа
iLimit = 180
# интервал
sInterval = '2h'
# количество результатов для выдачи
iCountPrint = 5

from binance_api import Binance

bot = Binance(API_KEY='D7...Ejj', API_SECRET='gwQ...u3A')

slKLines = bot.klines(symbol=sPair, interval=sInterval, limit=iLimit)

print(f'Анализируем пару {sPair} на интервале {sInterval} лимитом {iLimit}')

i = 0
# минимальная цена за весь период для покупки
fPriceMin = 99999999999999999.0
# максимальная цена за весь период для продажи
fPriceMax = 0.0
# уровни покупок
spBuy = []
# уровни продаж
spSell = []
import logging
import os
import time
from datetime import datetime

from binance_api import Binance

with open('config.json', 'r', encoding='utf-8') as fh:
    config = json.load(fh)

if 'api_key' not in config or 'secret_key' not in config:
    raise Exception(
        'Добавьте обязательные глобальные параметры api_key и/или secret_key в config.json'
    )
else:
    bot = Binance(API_KEY=config['api_key'], SECRET_KEY=config['secret_key'])

pairs = config['pairs']

for offset, elem in enumerate(pairs):
    if 'quote' not in pairs[offset] or 'base' not in pairs[offset]:
        raise Exception(
            'Добавьте обязательные локальные параметры quote и/или base для каждой пары в config.json'
        )

    pairs[offset]['interval'] = elem.get('interval', '5m')
    pairs[offset]['macd_fast_period'] = elem.get('macd_fast_period', 12)
    pairs[offset]['macd_slow_period'] = elem.get('macd_slow_period', 26)
    pairs[offset]['macd_signal_period'] = elem.get('macd_signal_period', 9)
    pairs[offset]['dom_offers_amount'] = elem.get('dom_offers_amount', 5)
    pairs[offset]['scalp_min'] = elem.get('scalp_min', 4) + 1
Beispiel #9
0
from binance_api import Binance
from config_api import API_key, API_sec

bot = Binance(API_KEY=API_key, API_SECRET=API_sec)


class BinanceBalance:
    #вызов метода с binance_api.py

    def showbalance(self):
        a = ('account', bot.account())
        your_balance = []

        #обрабатываю json файл, иду по элемнтам баланса

        for elem in a[1]['balances']:
            for i in elem:
                if elem['free'] != '0.00000000':
                    your_balance.append((elem['asset'], elem['free']))
                    break

        print("--------YOUR FREE BINANCE BALANCE---------\n")
        #вывожу данные в нормальном виде
        for elem in your_balance:
            for i in elem:
                print(i)


class MakeOrder:

    #LIMIT                         timeInForce, quantity, price
Beispiel #10
0
#import sqlite3    #Not required for this, but maybe in future to save to database instead
#import logging    #Not required yet, but maybe for logging on a bigger function
import time
import os
import math
import re
import csv
from datetime import datetime

from binance_api import Binance
import api_key

#Set up variables
API_KEY = api_key.API_ACCESS[0]
API_SECRET = api_key.API_ACCESS[1]
filename = 'pairs.csv'
history_header = [
    'Open time (milliseconds)', 'Open', 'High', 'Low', 'Close', 'Volume',
    'Close time (milliseconds)', 'Quote Asset Volume', '# Trades',
    'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore'
]
bot = Binance(API_KEY, API_SECRET)

symbols = bot.exchangeInfo()['symbols']
cur_pairs = {symbol['symbol']: symbol for symbol in symbols}

with open(filename, 'w', newline='\n') as myfile:
    wr = csv.writer(myfile)
    wr.writerow(cur_pairs)
from binance_api import Binance

bot = Binance(API_KEY='**********', API_SECRET='**********')
print('account', bot.account())
Beispiel #12
0
import sys
from datetime import datetime

from binance_api import Binance
import api_key

#Set up variables
API_KEY = api_key.API_ACCESS[0]
API_SECRET = api_key.API_ACCESS[1]

history_header = [
    'Open time (milliseconds)', 'Open', 'High', 'Low', 'Close', 'Volume',
    'Close time (milliseconds)', 'Quote Asset Volume', '# Trades',
    'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore'
]
bot = Binance(API_KEY, API_SECRET)
hist_symbol = 'BTCUSDT'
hist_interval = '1m'

#Get the data
#Iterate pairs

#Setup new history file
print('Retrieving market data for', hist_symbol)
filename = f"./logs/hist_{hist_symbol}_today.csv"
history_settings = f"Retrieved market data for {hist_symbol} at intervals of {hist_interval}"
with open(filename, 'w', newline='\n') as myfile:
    wr = csv.writer(myfile)
    wr.writerow(
        [history_settings]
    )  #[] wraps string in a list so it doesn't delimit the string as an array of characters
                "btc": 0
            },
            "margin_available": {
                "jpy": 0,
                "btc": 0
            }
        })

    """
    def info(self, params = {}):
        return self.coinCheck.request(ServiceBase.METHOD_GET, self.baseUrl, params)
    """


if __name__ == "__main__":
    from binance_api import Binance
    import os

    api_key = None
    secret_key = None
    with open(
            os.path.join(os.path.dirname(__file__),
                         "key/test_binance_key.txt")) as r:
        api_key = r.readline().strip()
        secret_key = r.readline().strip()

    api = Binance(api_key, secret_key)

    balance = api.account.balance()
    print(balance)
#Set up variables
API_KEY = api_key.API_ACCESS[0]
API_SECRET = api_key.API_ACCESS[1]
buy_min = 0.002
buy_max = 0.009
sell_min = 0.004
sell_max = 0.005
min_return = 0.01  #Only sell if you will make at least this much profit
history_header = [
    'Open time (milliseconds)', 'Open', 'High', 'Low', 'Close', 'Volume',
    'Close time (milliseconds)', 'Quote Asset Volume', '# Trades',
    'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore',
    'Percent change', 'Recommendation'
]
#Set up bot for API calls
bot = Binance(API_KEY, API_SECRET)
#Set up a list of symbol pairs to check, and wallet elements to show
#####
symbol = 'BTCUSDT'
interval = '1m'


def timestamp():
    ts = time.time() * 1000
    ts -= 0  #timezone offset in milliseconds
    return ts


def ticker(symbol):
    #Kline call to API for history of last minute only
    res = bot.klines(symbol=symbol, interval=interval, limit='1')
Beispiel #15
0
from binance_api import Binance
bot = Binance(API_KEY='D7...Ejj', API_SECRET='gwQ...u3A')
print('account', bot.account())
Beispiel #16
0
from binance_api import Binance
import datetime
import json
from db import sqliteDb
api = Binance(
    'AMWNxQ9DJ7t7ZKEAR8qT5boPYrdUIQHXUXBb7BgGb4fgKP53yK0YXaG9XPPkrJXU',
    'tSr4OaBiH0IXqXUNvVzsSRXyYpG314a03Yhltx9NQa9ok6M9h96YJwnu5BDMYGoa')
pattern = [["ETHUSDT", "LTCUSDT", "XLMUSDT", "XMRUSDT", "XEMUSDT"],
           ['1h', '1d']]
db = sqliteDb()
print('recording to db...   ' +
      datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S"))
for currency in pattern[0]:
    for interval in pattern[1]:
        responses = api.call_api(
            **{
                'command': 'klines',
                'symbol': currency,
                'interval': interval,
                'limit': 100
            })
        db.addToDb(currency, interval, json.dumps(responses))

db.close()
print('finished   ' + datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S"))
Beispiel #17
0
import json
#import binance_api
import our_library
'''
bot = binance_api.Binance(
    API_KEY='qRmmGsVlut46jEAYV6oKu6QuvEOrKPkg5aflmYkgmvOglBBbVl0ixMn8u1pf82sc',
    API_SECRET='GGw5Rr5fan9JC1dIhfyQMM5JFR5riPgCcM9wCUOk5NkUDbBaARAajKPlqUi1gx9R'
)
'''

from binance_api import Binance

bot = Binance(
    API_KEY='qRmmGsVlut46jEAYV6oKu6QuvEOrKPkg5aflmYkgmvOglBBbVl0ixMn8u1pf82sc',
    API_SECRET=
    'GGw5Rr5fan9JC1dIhfyQMM5JFR5riPgCcM9wCUOk5NkUDbBaARAajKPlqUi1gx9R')

data = bot.exchangeInfo()
our_library.record_in_file('exchangeInfo', data)
'''
data = bot.depth(symbol='BNBBTC')
our_library.record_in_file('depth', data)

data = bot.trades(symbol='BNBBTC')
our_library.record_in_file('trades', data)
'''
#data = bot.historicalTrades(symbol='BNBBTC', limit=5)
#our_library.record_in_file('historicalTrades', data)
'''
data = bot.aggTrades(symbol='BNBBTC')
our_library.record_in_file('aggTrades', data)
Beispiel #18
0
import json
from binance_api import Binance

bot = Binance(API_KEY='', API_SECRET='')


def record_in_file():
    my_file = open('B_time.txt', 'w')
    my_file.write(str(binance_time))
    my_file.close()
    print('Данные записаны в файл')


response_from_binance = bot.time()
print(response_from_binance)
binance_time = response_from_binance['serverTime']
print(binance_time)
record_in_file()
Beispiel #19
0
"""
    bot binance 
"""
import sqlite3
import logging
import time
import os

from datetime import datetime

from binance_api import Binance

bot = Binance(API_KEY='zvFmx2PyFOpIJbZmlO3T5ArHqGsE..........ozYn',
              API_SECRET='V4O2zb3Hn87pcOf7...............................zCd')
"""
    Prescribe the pairs that will be traded.
    base is the base pair(BTC, ETH, BNB, USDT) - what is written on the banner in the table above
    quote is a quota currency.For example, for trades on the NEO / USDT pair, the base currency is USDT, NEO is the quota
"""

pairs = [
    {
        'base': 'BTC',
        'quote': 'EOS',
        'offers_amount':
        5,  # How many offers from a glass we take to calculate the average price
        # Maximum 1000.The following values ​​are allowed:[5, 10, 20, 50, 100, 500, 1000]
        'spend_sum':
        0.0015,  # How much to spend base every time you buy a quote
        'profit_markup':
        0.005,  # What kind of profit is needed from each transaction?(0.001 = 0.1%)
import sys
from datetime import datetime

from binance_api import Binance
import api_key

#Set up variables
API_KEY = api_key.API_ACCESS[0]
API_SECRET = api_key.API_ACCESS[1]

history_header = [
    'Open time (milliseconds)', 'Open', 'High', 'Low', 'Close', 'Volume',
    'Close time (milliseconds)', 'Quote Asset Volume', '# Trades',
    'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore'
]
bot = Binance(API_KEY, API_SECRET)
hist_symbol = 'ETHUSDT'
hist_interval = '1m'
hist_interval_val = int(re.search(r'\d+', hist_interval).group())
#Convert interval value to #minutes based on hours or days if required
if hist_interval[-1] == 'h':
    hist_interval_val *= 60
if hist_interval[-1] == 'd':
    hist_interval_val *= 1440
hist_step = 60000 * hist_interval_val * 1000

#Get pairs
pairs = []
f = open('pairs.csv', 'r')
for pair in f:
    pairs.append(pair[:-1])
Beispiel #21
0
from binance_api import Binance
import time

bot = Binance(API_KEY='sdfgsdfb24g', API_SECRET='sdfag2q3')


def current_price():
    # print('ticker/bookTicker')
    x = bot.tickerBookTicker(symbol='ETHBTC')
    return float(x['askPrice'])


def order_price(koef):
    x = round(current_price() * koef, 6)
    print(x, koef)
    return x


def check_bars():
    data = bot.klines(symbol='ETHBTC', interval='1m', limit=1)
    print(data)
    for i in data:
        open_price = float(i[1])
        close_price = float(i[4])
        result = round(open_price * 1000000 - close_price * 1000000, 7)
        print(open_price, close_price, result)
        # if open_price*1000000 > close_price*1000000:
        #     print('more')
        #     break
        if result <= 0:
            print('false')
Beispiel #22
0
import csv
import json

from binance_api import Binance
bot = Binance(API_KEY='', API_SECRET='')


#запись данных в файл
def rec():
    i = bot.time('serverTime')
    my_file = open('time.txt', 'w')
    my_file.write(str(i))
    my_file.close()


print(bot.time())

json_string = bot.time()
#parsed_string = json.load(json_string)
print(json_string['serverTime'])
#parsed_string = ['serverTime']
'''
json_str = '{"serverTime": 1542267149637}'
json_prs = json.load(json_str)
print(json_prs['serverTime'])
'''
spisok_pokupok = {
    'Сметана': {
        'Name': "Сметана",
        'Price': 1.5,
        'Date': "11 ноября"
Beispiel #23
0
from binance_api import Binance

bot = Binance(API_KEY='', API_SECRET='')


def rm_klines(symbol, interval, limit):
    symbol = 'symbol=' + symbol
    interval = 'interval=' + interval
    list_klines = bot.klines(symbol='BTCUSDT', interval='1m', limit=1)
    list_klines = list_klines[0]
    return list_klines


# нужел ли вообще этот модуль?
def rm_time():
    list_time = bot.time()
    #list_time = int(time_check['serverTime'])
    return list_time
Beispiel #24
0
import os
import threading
import time
from dotenv import load_dotenv
from datetime import timedelta, datetime

from binance_api import Binance

logging.basicConfig(
    format=
    u'%(filename)s [LINE:%(lineno)d] #%(levelname)-8s [%(asctime)s]  %(message)s',
    level=logging.INFO,
    # level=logging.DEBUG,
)
load_dotenv()
bot1 = Binance(API_KEY=os.getenv("API_KEY1"),
               API_SECRET=os.getenv('API_SECRET1'))

bot2 = Binance(API_KEY=os.getenv('API_KEY2'),
               API_SECRET=os.getenv('API_SECRET2'))

settings1 = dict(
    symbol='BTCUSDT',  # Пара для отслеживания
    strategy="Short",  # Стратегия - Long (повышение), Short (понижение)
    stop_loss_perc=0.5,  # % оставания от цены
    stop_loss_fixed=
    0,  # Изначальный stop-loss, можно установить руками нужную сумму, потом бот подтянет.
    # Можно указать 0, тогда бот высчитает, возьмет текущую цену и применит к ней процент
    amount=
    0.0015,  # Кол-во монет, которое планируем продать (в случае Long) или купить (в случае Short)
    # Если указываем Long, то альты для продажи (Например, продать 0.1 ETH в паре ETHBTC)
    # Если Short, то кол-во, на которое покупать, например купить на 0.1 BTC по паре ETHBTC
Beispiel #25
0
import keys
from binance_api import Binance
import logging
import os
from binance.client import Client

longSQLiteGlb, longSQLiteGlbSell, shortSQLiteGlb, shortSQLiteGlbBuy = False, False, False, False
bot = Binance(API_KEY=keys.apikey, API_SECRET=keys.apisecret)
client = Client(keys.apikey, keys.apisecret)
#AppWorkLMT.updatePortfolio()
#assetsArray = client.get_account()

pairs_ = ['BTC', 'ETH', 'BAT', 'BNB', 'NEO', 'ADA', 'TRX', 'BTT', 'LTC', 'MATIC','ALGO','IOTA','XEM']
pairs_2 = ['USDT', 'BTC', 'ETH', 'BAT', 'BNB', 'NEO', 'ADA', 'TRX', 'BTT', 'LTC', 'MATIC','ALGO']
mprofit = ['0.05', '0.1', '0.2', '0.3', '0.4', '0.5','0.6','0.7','0.8','0.9','1','1.2', '1.5','2', '3','6', '8']
moffers_amount = ['5', '10', '20', '50', '100', '500', '1000']
mstoploss = ['0','0.05','0.1','0.15','0.2','0.25','0.3','0.35','0.4','0.45','0.5','0.55', '0.6', '0.7','0.9', '1', '1.5', '2', '3', '4', '5']
mDelay = ['5','10','15','30','60']
mKline = ['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h','1d','3d', '1w', '1M'] #For combobox in oop.py
#mKlinePeriod = ['5min ago UTC','15min ago UTC',  '30min ago UTC', '1H ago UTC','2H ago UTC', '6H ago UTC', '12H ago UTC','24H ago UTC','48H ago UTC','1W ago UTC', '1M ago UTC','now UTC']
mKlineLimit = ['2','3','6','11','16', '21', '51', '86', '101', '200', '300', '400', '500']
cmdays = ['-1 days','-7 days','-14 days','-30 days','-60 days','-90 days','-180 days','-360 days']
pairs = [
            {
                'base': 'USDT',
                'quote': 'BTC',
                #'offers_amount': 5,  # Сколько предложений из стакана берем для расчета средней цены
                # Максимум 1000. Допускаются следующие значения:[5, 10, 20, 50, 100, 500, 1000]
                'spend_sum': 25,  # Сколько тратить base каждый раз при покупке quote
                'spend_sum_mrg':0, # Сколько тратить base каждый раз при покупке quote - Маржинальная торпговля
                'profit_markup': 0.005,  # Какой навар нужен с каждой сделки? (0.001 = 0.1%)
Beispiel #26
0
def trade(init_settings: dict, file: str, bot: Binance, number: int):
    """Запускаем процесс трейлинга (по сути торгов) с заданными параметрами"""

    multiplier = -1 if init_settings['strategy'] == "Long" else 1

    # Получаем настройки пар с биржи
    symbols = bot.futuresExchangeInfo()['symbols']
    step_sizes = {symbol['symbol']: symbol for symbol in symbols}
    for symbol in symbols:
        for f in symbol['filters']:
            if f['filterType'] == 'LOT_SIZE':
                step_sizes[symbol['symbol']] = float(f['stepSize'])

    start_rate_bid, start_rate_ask = rates_market_info(init_settings, bot)

    timer = set_timer(init_settings['working_time'])

    while timer > datetime.now():
        try:
            bid, ask = rates_market_info(init_settings, bot)

            # Если играем на повышение, то ориентируемся на цены, по которым продают, иначе на цены, по которым покупают
            curr_rate = bid if init_settings['strategy'] == "Long" else ask

            # Если цена больше или равна установленному шагу и обратная сделка в процессе, доливаем с указанным
            # коэффициентом
            if init_settings['refund_flag'] and curr_rate >= init_settings['start_rate'] + \
                    (init_settings['start_rate'] * init_settings['grid_step'] / 100):
                init_settings['amount'], init_settings['start_rate'] = \
                    grid_step_set(init_settings['amount'], init_settings['coefficient'],
                                  init_settings['start_rate'], init_settings['grid_step'])

            if init_settings['stop_loss_fixed'] == 0:
                init_settings['stop_loss_fixed'] = (curr_rate / 100) * (
                    init_settings['stop_loss_perc'] * multiplier + 100)

            logging.info(
                f"Bot#{number}: Текущие курсы {init_settings['symbol']} bid {bid:0.8f}, ask {ask:0.8f}, выбрана {curr_rate:0.8f} "
                f"stop_loss {init_settings['stop_loss_fixed']:0.8f}")

            # Считаем, каким был бы stop-loss, если применить к нему %
            curr_rate_applied = (curr_rate / 100) * (
                init_settings['stop_loss_perc'] * multiplier + 100)

            if init_settings['strategy'] == "Long":
                # Выбрана стратегия Long, пытаемся продать монеты как можно выгоднее
                write_to_file(file, f"{curr_rate:0.8f}",
                              f"{init_settings['stop_loss_fixed']:0.8f}")
                if curr_rate > init_settings['stop_loss_fixed']:
                    logging.info(
                        f"Bot#{number}: Текущая цена выше цены Stop-Loss")
                    if curr_rate_applied > init_settings['stop_loss_fixed']:
                        logging.info(
                            f"Bot#{number}: Пора изменять stop-loss, новое значение {curr_rate_applied:0.8f}"
                        )
                        init_settings['stop_loss_fixed'] = curr_rate_applied
                else:
                    # Текущая цена ниже или равна stop loss, продажа по рынку
                    profit_check = start_rate_bid - curr_rate - (curr_rate *
                                                                 0.0002)
                    if profit_check > 0 or (profit_check <= 0 and
                                            init_settings['no_profit_flag']):
                        res = create_order("SELL", init_settings, bot)
                        logging.info(
                            f'Bot#{number}: Результат создания ордера', res)
                        if 'orderId' in res:
                            # Создание ордера прошло успешно, выход
                            logging.info(
                                f"Bot#{number}: Сделка по паре {res['symbol']} {init_settings['strategy']} "
                                f"успешно закрыта по цене {res['price']}")
                            init_settings['count_fails'] = 0
                            break
                    else:
                        # Запускаем сделку в обратную сторону, согласно стратегии
                        init_settings, timer = refunding_try(
                            init_settings, curr_rate)

            else:
                write_to_file(file, f"{curr_rate:0.8f}",
                              f"{init_settings['stop_loss_fixed']:0.8f}")
                # Выбрана стратегия Short, пытаемся купить монеты как можно выгоднее
                if curr_rate < init_settings['stop_loss_fixed']:
                    logging.info(f"Bot#{number}: Текущая цена ниже stop-loss")
                    if curr_rate_applied < init_settings['stop_loss_fixed']:
                        logging.info(
                            f"Bot#{number}: Пора изменять stop-loss, новое значение {curr_rate_applied:0.8f}"
                        )
                        init_settings['stop_loss_fixed'] = curr_rate_applied
                else:
                    # Цена поднялась выше Stop-Loss, Покупка по рынку
                    quantity = math.floor(
                        (init_settings['amount'] / curr_rate) *
                        (1 / step_sizes[init_settings['symbol']])) / (
                            1 / step_sizes[init_settings['symbol']])
                    logging.info(
                        f"Bot#{number}: Цена поднялась выше Stop-Loss, Покупка по рынку, "
                        f"кол-во монет {quantity:0.8f}")
                    profit_check = start_rate_ask - curr_rate - (curr_rate *
                                                                 0.0002)
                    if profit_check > 0 or (profit_check <= 0 and
                                            init_settings['no_profit_flag']):
                        res = create_order("BUY", init_settings, bot)
                        logging.info(
                            f"Bot#{number}: Результат создания ордера", res)
                        if 'orderId' in res:
                            # Создание ордера прошло успешно, выход
                            logging.info(
                                f"Bot#{number}: Сделка по паре {res['symbol']} {init_settings['strategy']} "
                                f"успешно закрыта по цене {res['price']}")
                            init_settings['count_fails'] = 0
                            break
                    else:
                        # Запускаем сделку в обратную сторону, согласно стратегии
                        init_settings, timer = refunding_try(
                            init_settings, curr_rate)

        except Exception as e:
            logging.error(e)
        time.sleep(0.5)
Beispiel #27
0
"""
    Подробная информация о боте на сайте bablofil.ru/bot-dlya-binance
"""
import sqlite3
import logging
import time
import os
import math

from datetime import datetime

from binance_api import Binance

bot = Binance(
    API_KEY='',
    API_SECRET=''
)

settings = dict(
    symbol='EOSBTC',            # Пара для отслеживания
    strategy="Short",           # Стратегия - Long (повышение), Short (понижение)           
    stop_loss_perc = 0.5,       # % оставания от цены
    stop_loss_fixed = 0,        # Изначальный stop-loss, можно установить руками нужную сумму, потом бот подтянет.
                                # Можно указать 0, тогда бот высчитает, возьмет текущую цену и применит к ней процент
    amount = 0.0015             # Кол-во монет, которое планируем продать (в случае Long) или купить (в случае Short)
                                # Если указываем Long, то альты для продажи (Например, продать 0.1 ETH в паре ETHBTC)
                                # Если Short, то кол-во, на которое покупать, например купить на 0.1 BTC по паре ETHBTC
)

multiplier = -1 if settings['strategy'] == "Long" else 1
Beispiel #28
0
#Бот для trailing stop (на примере Binance)

import sqlite3
import logging
import time
import os
import math
from datetime import datetime
from binance_api import Binance

bot = Binance(
    API_KEY='RzP45uN1Vk1izyxino2rNvqOHSLu2FO9JbA2gQ3UGcfiHzjCIdp1xkQoZyqXk3jz',
    API_SECRET=
    'zar0z7felabYwTZ0lCz8CW6wXZLLKqUDvP588Z2X8sSkh1iNbsW0HMWy1Pq6HmXA')

coin1 = 'LOOM'
coin2 = 'BTC'
settings = dict(
    symbol=coin1 + coin2,  # Пара для отслеживания
    strategy="SELL",  # Стратегия - SELL (повышение), BUY (понижение)           
    stop_loss_perc=1,  # % оставания от цены
    stop_loss_fixed=
    0.00006000,  # Изначальный stop-loss, можно установить руками нужную сумму, потом бот подтянет.
    # Можно указать 0, тогда бот высчитает, возьмет текущую цену и применит к ней процент
    amount=
    0.00001  # Кол-во монет, которое планируем продать (в случае SELL) или купить (в случае BUY)
    # Если указываем SELL, то альты для продажи (Например, продать 0.1 ETH в паре ETHBTC)
)  # Если BUY, то кол-во, на которое покупать, например купить на 0.1 BTC по паре ETHBTC

# Получаем ограничения торгов по всем парам с биржи
limits = bot.exchangeInfo()  # Наши жесткие ограничения перечислены
Beispiel #29
0
# интервал
sInterval = '2h'
# количество результатов для выдачи
iCountPrint = 5
# минимальное количество сделок
iCountTrade = 4

print(
    f'Запускаем анализ всех пар по валюте {sBase}. Выводы в estimation.txt \n')

# будем писать в файл

sys.stdout = open('estimation.txt', 'wt', encoding='utf-8')

# подключаемся к бирже
bot = Binance(API_KEY='D7...Ejj', API_SECRET='gwQ...u3A')

#  интересующие пары
lPairs = []

# данные по торгуемым парам

lExchangeInfo = bot.exchangeInfo()
iCountPair = 0
lTicker = []
for lEI in lExchangeInfo['symbols']:
    # print(lEI)
    # print(lEI['status'])
    if (lEI['status'] == 'TRADING') and ((lEI['baseAsset'] == sBase) or
                                         (lEI['quoteAsset'] == sBase)):
        lTicker24h = bot.ticker24hr(symbol=lEI['symbol'])
Beispiel #30
0
from binance.client import Client
from binance.enums import *
from binance_api import Binance  # bot
import source5 as src
# Работа со временем
import time
import datetime as dt
# Работа с вычислениями
import math
#######################################################

BINANCE_API = '9UD74nMGt7MK1Ar2awpNqeRh5R0fP2AeMfd9obImCoZwu6DPYGho30oPwSlqVlXt'
BINANCE_SECRET = 'nWQonlvsNw0hKGMuzTSRN0hLWt5S2nbIqw7QV6PA0ZRtpCu6ctjHTcFFCXIAJT7M'
botR = Binance(API_KEY=BINANCE_API, API_SECRET=BINANCE_SECRET)
# for real trading and prices
clientR = Client(BINANCE_API, BINANCE_SECRET)
SOCKET = "wss://stream.binance.com:9443/ws/busdusdt@kline_1m"  #  котировки с реального счета
#SOCKET = "wss://stream.binance.com:9443/ws/busdusdt@kline_1m"  #  котировки с реального счета
# for testnet trading -----------------------------------------------------------------------  менять  !!!!!!!!!
TEST_BINANCE_API = 'lueE5N8CXAfcCByFaYPebvqtaLYqQwmcS3MhLRKdtunOqBr2WkKgJb4Sxm32JWtr'
TEST_BINANCE_SECRET = 'pmjbtHJWW2HwzweQnNQ7Qos8ZIHQXPjTsUa21FcKobGDq6SGDNwhoKKFvVnl6GWx'
botT = Binance(API_KEY=TEST_BINANCE_API, API_SECRET=TEST_BINANCE_SECRET)
test_client = Client(TEST_BINANCE_API, TEST_BINANCE_SECRET)
test_client.API_URL = 'https://testnet.binance.vision/api'
test_socket = "wss://testnet.binance.vision/ws/busdusdt@kline_1m"

# global variables =========================================================================
BASE = 'BUSD'  #def= "BNB" -БАЗОВАЯ КРИПТОВАЛЮТА
QUOTE = "USDT"  #                      -КВОТИРУЕМАЯ
SYMBOL = BASE + QUOTE
ASSET = SYMBOL