예제 #1
0
 def _init_client(self):
     self.client = Client(self.api_key,self.api_secret)
     self.socket_manager = BinanceSocketManager(self.client)
from binance.client import Client
from binance.websockets import BinanceSocketManager

#api_key = 'wEfVeIfGmq5YwKCrI8LCFycWp4M4jTMHG1HVprtfZP7jfyxeZybVuVibO5GyJ82j'
#api_secret = 'wQlqm6SFJtWphpl0ChCelgmeZLphvM3ynQqCeTOam6jYuQJFhcLfE1DEavWfnkTO'

client = Client('', '')


def process_message(msg):
    print("message type: {}".format(msg['e']))
    print(msg)
    # do something


def process_depth_message(msg):
    print('----depth-----')
    print(msg)


bm = BinanceSocketManager(client)
bm.start_aggtrade_socket(symbol='ETHBTC', callback=process_message)
bm.start_depth_socket(symbol='ETHBTC', callback=process_depth_message)
bm.start()


def process_m_message(msg):
    print('---------start_multiplex_socket msg----')
    print("message type: {}".format(msg['e']))
    print(msg)
예제 #3
0
from binance.client import Client
client = Client(
    'FULgMs4X94itKmsHtke5J7SMyb6fUPXENomyS3iE6VO0sXnrLmoc5rTOegEn5248',
    'CYyhgBG0xknpS7pD1iPDigzXYTr957gV3p88aqlqPpZmDzyb8sbWCBRYv55FaU9v')

# get market depth
depth = client.get_order_book(symbol='BNBBTC')

# place a test market buy order, to place an actual order use the create_order function
order = client.create_test_order(symbol='BNBBTC',
                                 side=Client.SIDE_BUY,
                                 type=Client.ORDER_TYPE_MARKET,
                                 quantity=100)

# get all symbol prices
prices = client.get_all_tickers()

# withdraw 100 ETH
# check docs for assumptions around withdrawals
from binance.exceptions import BinanceAPIException, BinanceWithdrawException
try:
    result = client.withdraw(asset='ETH', address='<eth_address>', amount=100)
except BinanceAPIException as e:
    print(e)
except BinanceWithdrawException as e:
    print(e)
else:
    print("Success")

# fetch list of withdrawals
withdraws = client.get_withdraw_history()
예제 #4
0
        self.candleClose = currCandle[4]
        self.candleVolume = currCandle[5]
        self.quoteAssetVolume = currCandle[7]
        self.numberTrade = currCandle[8]
        self.takerBuyBaseAssetVol = currCandle[9]
        self.takerBuyQuoteAssetVol = currCandle[10]


class coinClass:
    def __init__(self, coinName, allCandleObjects):
        self.name = coinName
        self.allCandleObjects = allCandleObjects


#Initializes keys and links to exchange account
api_key = 'CFQvKQ9Xuf7L6mf8i7qqCoDmrK9C6XzGibUWXvTB4nagC3OblBlMTj49BNHV3qjN'
api_secret = 'PTJVaWQd9DCW2ysn7ATdLf1T9F8eheEe29mEVfIx9BML92N1dC95nk7jfn8tFplM'
client = Client(api_key, api_secret)

tickers = client.get_all_tickers()

coinNames = []

for tick in tickers:
    coin = tick['symbol']
    if coin[-4:] == 'USDT':
        if coin not in coinNames:
            coinNames.append(coin)

print(len(coinNames))
print(coinNames)
예제 #5
0
        count += 1
    return high, low


def min_max(min, max, val):
    if min > val:
        min = val
    if max < val:
        max = val
    return min, max


# place your keys here from Bianance
api_key = ''
secret_key = ''
client = Client(api_key, secret_key)

# Enter coin in caps, between '', seperated by comma
myCoin = ['XRP', 'VIBE', 'XVG', 'ADA', 'XLM']
createFile(myCoin)
values = readFile()
createList(values)
# enter whatever currency you prefer, i.e. EUR
exchange = 'USD'
# enter whatever exchange you prefer, i.e. BTC
exchangeCoin = 'ETH'
amtInvested = 1250

var_minutes = .5
var_time = var_minutes * 60
iterations = 24 * 60 / var_minutes
예제 #6
0
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 19 17:46:32 2018

@author: jackson
"""
import key
import datetime
from time import sleep
from binance.client import Client
client = Client(key.api_key, key.api_secret)

symbol = 'BTCUSDT'
quantity = '0.05'

order = False
while order == False:
    BTC = client.get_historical_klines(symbol=symbol,
                                       interval='30m',
                                       start_str="1 hour ago UTC")
    if (float(BTC[-1][4]) - float(BTC[-2][4])) > 5:
        print('Buyyy')
        #client.order_market_buy(symbol= symbol, quantity= quantity)
        order = True
    elif (float(BTC[-1][4]) - float(BTC[-2][4])) < -5:
        print('Sellll')
        #client.order_market_buy(symbol= symbol , quantity= quantity)
        order = True
    else:
        print('Do nothing')
    sleep(5)
예제 #7
0
import json
import time
import schedule
import binanceKeys
import os

from pync import Notifier
from binance.client import Client

#connect to Binance API
binance_client = Client(binanceKeys.apiKey, binanceKeys.secretKey)

def job():

    config = None

    with open ("config.json") as file:
        config = json.load(file)

    for market in config.get("markets"):

        if market["active"] is False:
            continue

        symbol = market["name"]
        max_price = market["max"]
        min_price = market["min"]
        ticker = binance_client.get_symbol_ticker(symbol=symbol)
        price = float(ticker.get("price"))

        if price > max_price or price < min_price:
from binance.client import Client
from binance.websockets import BinanceSocketManager
from binance.enums import *
import time
import threading
import winsound

# Replace your_api_key, your_api_secret with your api_key, api_secret
client = Client(your_api_key, your_api_secret)


# Calculate list of symbols
def calculate_data_list():
    counter = 0
    btc = 'BTC'
    symbols = []
    all_positions = []
    positions_final = []
    volume = []
    c = []
    price_change = []
    data = client.get_ticker()
    for x in range(len(data)):
        if (
                btc in data[x]['symbol']
        ) and data[x]['symbol'] != 'BTCUSDT' and data[x]['symbol'] != 'VENBTC':
            if float(data[x]['quoteVolume']) > 100:
                all_positions.append(x)
    for x in all_positions:
        c.append(float(data[x]['priceChangePercent']))
    i = sorted(range(len(c)), key=lambda k: c[k])
예제 #9
0
import os.path
import time
from mykeys import *
from bitmex import bitmex
from binance.client import Client
from datetime import timedelta, datetime
from dateutil import parser
from tqdm import tqdm_notebook  #(Optional, used for progress-bars)

### CONSTANTS
binsizes = {"1m": 1, "5m": 5, "1h": 60, "1d": 1440}
batch_size = 750
bitmex_client = bitmex(test=False,
                       api_key=bitmex_api_key,
                       api_secret=bitmex_api_secret)
binance_client = Client(api_key=binance_api_key, api_secret=binance_api_secret)


class DataLoader:
    def minutes_of_new_data(self, symbol, kline_size, data, source):
        if len(data) > 0: old = parser.parse(data["timestamp"].iloc[-1])
        elif source == "binance":
            old = datetime.strptime('1 Jan 2017', '%d %b %Y')
        elif source == "bitmex":
            old = bitmex_client.Trade.Trade_getBucketed(
                symbol=symbol, binSize=kline_size, count=1,
                reverse=False).result()[0][0]['timestamp']
        if source == "binance":
            new = pd.to_datetime(binance_client.get_klines(
                symbol=symbol, interval=kline_size)[-1][0],
                                 unit='ms')
예제 #10
0
from binance.client import Client
import numpy as np
import talib as ta
from talib import MA_Type
import time
import re
import requests
from decimal import *
from reFunc import *
import datetime

getcontext().prec = 4
binance = Client('apiKey', 'apiSecret')
checkSqlite()
ceptekiPara = 720
while True:
    for i in range(len(coinP)):
        if len(getOpenOrder()) < 24:
            if orderCheck(coinP[i]):# and dateCheck(coinP[i]): 
                try:
                    interval = '1h'
                    pair = coinP[i] 
                    limit = 500
                    klines = binance.get_klines(symbol=pair, interval=interval, limit=limit)

                    #open_time = [int(entry[0]) for entry in klines]
                    #open = [float(entry[1]) for entry in klines]
                    high = [float(entry[2]) for entry in klines]
                    low = [float(entry[3]) for entry in klines]
                    close = [float(entry[4]) for entry in klines]
                    #volume = [float(entry[5]) for entry in klines]
예제 #11
0
def index():
    client = Client(app.config['API_KEY'], app.config['API_SECRET'])
    prices = client.get_all_tickers()

    url = 'http://data.fixer.io/api/latest?access_key=87fdd450a053ec762d421382f62b7ad7&symbols=USD,CNY'
    req = request.Request(url)
    res = request.urlopen(req)
    res = res.read()
    resjson = json.loads(res)
    usdrate = resjson["rates"]["USD"]
    cnyrate = resjson["rates"]["CNY"]
    fex = float(cnyrate / usdrate)

    mybtc = mydb.session.query(
        Btc.symbol,
        func.sum(Btc.amount).label('amount'),
        func.sum(Btc.cnycost).label('cnycost')).group_by(Btc.symbol).all()
    mybase = mydb.session.query(func.sum(Base.invest).label('invest')).first()
    mybaseinvest = mybase.invest

    portfolio = {}

    mybtclist = {}
    for symbol in prices:
        mybtclist[symbol['symbol']] = symbol['price']

    cnysum = float(0)
    for coin in mybtc:
        if coin.symbol + "USDT" in mybtclist:
            cnyprice = float(
                mybtclist[coin.symbol + "USDT"]) * fex  #*float(coin.amount)
            portfolio[coin.symbol] = [
                coin.amount, coin.cnycost,
                round(float(coin.cnycost) / float(coin.amount), 2), cnyprice,
                round(cnyprice, 2),
                round((cnyprice * float(coin.amount) - float(coin.cnycost)) /
                      (float(coin.cnycost)) * 100, 2)
            ]
        elif coin.symbol + "ETH" in mybtclist:
            cnyprice = float(mybtclist[coin.symbol + "ETH"]) * float(
                mybtclist['ETHUSDT']) * fex  #*float(coin.amount)
            portfolio[coin.symbol] = [
                coin.amount, coin.cnycost,
                round(float(coin.cnycost) / float(coin.amount), 2), cnyprice,
                round(cnyprice, 2),
                round((cnyprice * float(coin.amount) - float(coin.cnycost)) /
                      (float(coin.cnycost)) * 100, 2)
            ]
        else:
            cnyprice = float(mybtclist[coin.symbol + "BTC"]) * float(
                mybtclist['BTCUSDT']) * fex  #*float(coin.amount)
            portfolio[coin.symbol] = [
                coin.amount, coin.cnycost,
                round(float(coin.cnycost) / float(coin.amount), 2), cnyprice,
                round(cnyprice, 2),
                round((cnyprice * float(coin.amount) - float(coin.cnycost)) /
                      (float(coin.cnycost)) * 100, 2)
            ]
        cnysum = cnysum + float(portfolio[coin.symbol][3] * float(coin.amount))

    gain = round((cnysum / float(mybaseinvest) - 1) * 100, 2)

    cnysumround = float('%.2f' % cnysum)
    mybaseinvestround = float('%.2f' % mybaseinvest)

    return render_template('index.html',
                           prices=prices,
                           fex=fex,
                           mybtc=mybtc,
                           portfolio=portfolio,
                           cnysumround=cnysumround,
                           mybaseinvestround=mybaseinvestround,
                           gain=gain)
예제 #12
0
from flask import Flask, render_template, session, copy_current_request_context, request, make_response
from flask_socketio import SocketIO, emit, disconnect
from threading import Lock

from threading import Thread, Event
import time

from binance.client import Client
from binance.websockets import BinanceSocketManager
from app.config import BINANCE_CREDENTIALS, USER_LOGIN

client = Client(BINANCE_CREDENTIALS['KEY'], BINANCE_CREDENTIALS['SECRET'])

async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socket_ = SocketIO(app, async_mode=async_mode)
# thread = None
# thread_lock = Lock()
thread = Thread()
thread_stop_event = Event()
conn_key = ""
count = 0


def emit_data(msg):
    global count
    if msg['e'] != 'error':
        btc_price = float(msg['c'])
        socket_.emit('my_response', {
            'data': str(count),
    TRAILING_STOP_LOSS = parsed_config['trading_options']['TRAILING_STOP_LOSS']
    TRAILING_TAKE_PROFIT = parsed_config['trading_options'][
        'TRAILING_TAKE_PROFIT']
    SIGNALLING_MODULES = parsed_config['trading_options']['SIGNALLING_MODULES']
    if DEBUG_SETTING or args.debug:
        DEBUG = True

    # Load creds for correct environment
    access_key, secret_key = load_correct_creds(parsed_creds)

    if DEBUG:
        print(f'loaded config below\n{json.dumps(parsed_config, indent=4)}')
        print(f'Your credentials have been loaded from {creds_file}')

    # Authenticate with the client, Ensure API key is good before continuing
    client = Client(access_key, secret_key)
    api_ready, msg = test_api_key(client, BinanceAPIException)
    if api_ready is not True:
        exit(msg)

    # Use CUSTOM_LIST symbols if CUSTOM_LIST is set to True
    if CUSTOM_LIST: tickers = [line.strip() for line in open('tickers.txt')]

    # try to load all the coins bought by the bot if the file exists and is not empty
    coins_bought = {}

    # path to the saved coins_bought file
    coins_bought_file_path = 'coins_bought.json'

    # rolling window of prices; cyclical queue
    historical_prices = [None] * (TIME_DIFFERENCE * RECHECK_INTERVAL)
예제 #14
0
    def Buy(self):
        variablebuy = 1
        if self.RSI <= 20 and self.StochRSIK <= 20 and self.MoneyFlow <= 20:
            print("There is an BUY Signal with {v1} on the {v2} chart.".format(
                v1=self.TradingPair, v2=self.TimeFrame))
        else:
            #print("There are no buy signals with {v1} on the {v2} chart.".format(v1=self.TradingPair,v2=self.TimeFrame))
            variablebuy = 2
        return variablebuy

    def Sell(self):
        variablesell = 1
        if 80 <= self.RSI and 80 <= self.StochRSIK and 80 <= self.MoneyFlow:
            print("There is a SELL Signal with {v1} on the {v2} chart.".format(
                v1=self.TradingPair, v2=self.TimeFrame))
        else:
            #print("There are no sell signals with {v1} on the {v2} chart.".format(v1=self.TradingPair,v2=self.TimeFrame))
            variablesell = 2
        return variablesell


if __name__ == "__main__":
    client = Client(Keys.APIKey, Keys.SecretKey)
    BTCUSDT = Alerts("BTCUSDT", client.KLINE_INTERVAL_1DAY, 11, 22, 33, 44)

    list1 = ["ABC", "DEF", "HIJ"]
    for i in list1:
        Alert = Alerts(i, client.KLINE_INTERVAL_1DAY, 11, 22, 33, 44)
        Alert.Buy()
예제 #15
0
API_SECRET = ""
"""определяем списки, в которые будут попадать данные из стрима биржи"""
openes_1h = []
highes_1h = []
lowes_1h = []
closes_1h = []

closes_15m = []
openes_15m = []
highes_15m = []
lowes_15m = []
"""чтобы не было постоянных попыток сделать ордер при выполнении определённых условий,
   введем переменную in_position"""
in_position = False

client = Client(API_KEY, API_SECRET, tld='com')


#задаём функцию, которая размещает ордер по рыночной цене
def order(side, quantity, symbol, order_type=ORDER_TYPE_MARKET):
    try:
        print("sending order")
        make_order = client.create_order(symbol=symbol,
                                         side=side,
                                         type=order_type,
                                         quantity=quantity)
        print(make_order)
    except Exception as e:
        print("an exception occured - {}".format(e))
        return False
예제 #16
0
from binance.client import Client
from binance.websockets import BinanceSocketManager
import pymongo

client = Client("a", "b")

bm = BinanceSocketManager(client)

# collection is mongo is same as a Table

myclient_1 = pymongo.MongoClient(
    "mongodb://*****:*****@ds243254.mlab.com:43254/gvtbtc")
mydb_1 = myclient_1["gvtbtc"]
mycol_1 = mydb_1["data"]

myclient_2 = pymongo.MongoClient(
    "mongodb://*****:*****@ds245234.mlab.com:45234/mdabtc")
mydb_2 = myclient_2["mdabtc"]
mycol_2 = mydb_2["data"]

myclient_3 = pymongo.MongoClient(
    "mongodb://*****:*****@ds243254.mlab.com:43254/eosbtc")
mydb_3 = myclient_3["eosbtc"]
mycol_3 = mydb_3["data"]

myclient_4 = pymongo.MongoClient(
    "mongodb://*****:*****@ds243254.mlab.com:43254/adabtc")
mydb_4 = myclient_4["adabtc"]
mycol_4 = mydb_4["data"]  # collection is mongo is same as a Table

myclient_5 = pymongo.MongoClient(
예제 #17
0
        type=str,
        default='10000.0',
        required=False,
        help="Percentage increase from buy price at which to sell")
    args = parser.parse_args()

    # get public and private keys
    public_key, private_key = get_keys(test=False)

    # ensure wait arg is specified with a non zero value
    assert args.wait != 0, "ERROR: must specify a non zero value for --wait, use 'python pymp.py -h' for help"
    pct = float(args.pct)
    pump_btc = float(args.btc)

    # create new client obj
    client = Client(public_key, private_key)
    print("Session initiated with Binance API")
    # client.API_URL = "https://testnet.binance.vision/api"  # for testing

    # get BTC balance and assert there is enough in account
    btc_acc_amt = round(float(client.get_asset_balance(asset="BTC")['free']),
                        8)
    assert btc_acc_amt >= pump_btc, "ERROR: insufficient BTC funds in account, specify a smaller value for --btc"

    # Wait for pump command
    coin = input(
        "Ready. Awaiting coin symbol input:").upper().strip()  # pump coin
    symbol = f"{coin}BTC"  # exchange symbol
    while client.get_symbol_info(symbol) is None:
        print("ERROR: inputted coin symbol is wrong!!!")
        coin = input("Re-enter coin symbol:").upper().strip()
예제 #18
0
파일: server.py 프로젝트: froyobin/http_led
 def __init__(self, *args, **kwargs):
     self.binance_client = Client(api_key, api_secret)
     super().__init__(*args, **kwargs)
예제 #19
0
#this code is used in the app.py file too

import config, csv
from binance.client import Client

client = Client(config.API_KEY, config.API_SECRET)

#Show all tickers/trading pairs available
#prices = client.get_all_tickers()
#for price in prices:
#    print(price)

#used in the part of the code to save a file with stream data
#get_klines return 500 candlesticks in a list of lists
#candles = client.get_klines(symbol='BTCUSDT', interval=Client.KLINE_INTERVAL_15MINUTE)

csvfile = open('daily.csv', 'w', newline='')
candlestick_writer = csv.writer(csvfile, delimiter=',')

#the code below is to write the stream in a csv file
#for candlestick in candles:
#    print(candlestick)
#    candlestick_writer.writerow(candlestick)
#print(len(candles))

candlesticks = client.get_historical_klines("BTCUSDT",
                                            Client.KLINE_INTERVAL_1DAY,
                                            "1 Jan, 2012", "22 Sep, 2020")
for candlestick in candlesticks:
    candlestick_writer.writerow(candlestick)
csvfile.close()
예제 #20
0
from binance.client import Client
from binance.agent import Agent
from binance.tokenpair import TokenPair
import pickle

API_KEY = '6qU8SOwMNuSCnQsUddXcFPt6e3jkQPOhhsM77H4Y2gQc6oXFjrDdXmIdsdXrkfXZ'
API_SECRET = '6S31vqIj54vQ9FQKKue6FMulMSxGZh5DxizjZOlXuDvq7LIKHYzAFkVTNhoX2j3Y'

client = Client(API_KEY, API_SECRET)
# info = client.get_account()
# print "info: ", info
# balance = client.get_asset_balance(asset='BTC')
# print "balance: ", balance
# status = client.get_account_status()
# print "status: ", status
# tickers = client.get_ticker(symbol="BNBBTC")
# print(tickers)

# create token pair to monitor and trading
BNNBTC_pair = TokenPair(client, "BNBBTC")
VENETH_pair = TokenPair(client, "VENETH")
ONTETH_pair = TokenPair(client, "ONTETH")

agent = Agent(client)
# our token must add these tokens in order to perform action like: monitoringm trading...
agent.add_token_pair(BNNBTC_pair)
agent.add_token_pair(VENETH_pair)
agent.add_token_pair(ONTETH_pair)
# run the agent
agent.run()
예제 #21
0
파일: ArBot.py 프로젝트: Fuadain/ArBot
from binance.client import Client
import time
from decimal import Decimal
import msvcrt as m
import math

client = Client(key, secret)

print("Connected")


def pauseProgram():
    # Pause program in case of errors and help with debugging
    print("Waiting until key press to allow error study")
    m.getch()
    print(
        "Key has been pressed, now waiting 1,000,000 seconds to continue program"
    )
    time.sleep(1000000)


def coinSearch(coin):
    print("Searching for trades in " + coin)
    try:
        # BTC conversion prices for bnb and eth are found
        bnbBtc = client.get_symbol_ticker(symbol="BNBBTC")
        time.sleep(0.05)
        ethBtc = client.get_symbol_ticker(symbol="ETHBTC")
        time.sleep(0.05)
        bnbBtcPrice = Decimal(bnbBtc.get("price"))
        ethBtcPrice = Decimal(ethBtc.get("price"))
예제 #22
0
from binance.client import Client
import datetime
import pickle
import queue
import sys

# NOTE THIS FILE WILL NOT WORK WITHOUT THESE VARIABLE SET TO A VALID SET OF TOKENS AN KEYS
token = ''
key = ''
client = Client(token, key)
trade_symbol = 'BTCUSDT'


# month, days are integer, day_end is inclusive
# translator for the API call client.get_klines
def get_klines(month, day_start, day_end):

    candles = []

    klimit = 480  # 480 minutes = 8 hours, each
    thirds_of_day = ['00', '08',
                     '16']  # based on hour of the day ie midnight, etc

    for day in range(day_start, day_end + 1):

        for third in range(0, 3):

            dt_obj = datetime.datetime.strptime(
                str(day) + '.' + str(month) + '.2018 ' + thirds_of_day[third] +
                ':00:00,00', '%d.%m.%Y %H:%M:%S,%f')
            timestamp = (int)(dt_obj.timestamp() * 1000)
예제 #23
0
from django.db import models
from django.db.models import Max

from .exchangeinfo import ExchangeInfo
from binance.client import Client

BinanceClient = Client(
    "y4IYuRu7rcBuBRxbT57hdrUE12UpvMZdzJOdqPGrdS4jTU2oi9onl4bNxvZ6qMEj",
    "BZ3y4qZ8019zzU6F2hv4WLbDnpeIQMBIuefMHxb1qPeloUayZUbOv1Che8Fzy34C")


class Candle(models.Model):
    KLINE_INTERVAL = [
        (Client.KLINE_INTERVAL_1MINUTE, Client.KLINE_INTERVAL_1MINUTE),
        (Client.KLINE_INTERVAL_3MINUTE, Client.KLINE_INTERVAL_3MINUTE),
        (Client.KLINE_INTERVAL_5MINUTE, Client.KLINE_INTERVAL_5MINUTE),
        (Client.KLINE_INTERVAL_15MINUTE, Client.KLINE_INTERVAL_15MINUTE),
        (Client.KLINE_INTERVAL_30MINUTE, Client.KLINE_INTERVAL_30MINUTE),
        (Client.KLINE_INTERVAL_1HOUR, Client.KLINE_INTERVAL_1HOUR),
        (Client.KLINE_INTERVAL_2HOUR, Client.KLINE_INTERVAL_2HOUR),
        (Client.KLINE_INTERVAL_4HOUR, Client.KLINE_INTERVAL_4HOUR),
        (Client.KLINE_INTERVAL_6HOUR, Client.KLINE_INTERVAL_6HOUR),
        (Client.KLINE_INTERVAL_8HOUR, Client.KLINE_INTERVAL_8HOUR),
        (Client.KLINE_INTERVAL_12HOUR, Client.KLINE_INTERVAL_12HOUR),
        (Client.KLINE_INTERVAL_1DAY, Client.KLINE_INTERVAL_1DAY),
        (Client.KLINE_INTERVAL_3DAY, Client.KLINE_INTERVAL_3DAY),
        (Client.KLINE_INTERVAL_1WEEK, Client.KLINE_INTERVAL_1WEEK),
        (Client.KLINE_INTERVAL_1MONTH, Client.KLINE_INTERVAL_1MONTH)
    ]

    symbol = models.ForeignKey(ExchangeInfo, on_delete=models.CASCADE)
예제 #24
0
import time
import sys
import math
import datetime, getopt
import pandas as pd
from binance.client import Client

client = Client("","")

class trader:

    
    def getLastCandleOpen(_pair):
        data = client.get_historical_klines(symbol=_pair, interval= '2h', start_str= '4 hour ago UTC')
        data_df= pd.DataFrame(data, columns=['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time', 'Quote asset volume', 'Number of trades', 'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore'])
        return str(data_df['Open'][0]);


    def makeTradeBuy(_pair,_toSell,_type):
        _price = float(client.get_ticker(symbol=_pair)["lastPrice"])
        _balance = float(client.get_asset_balance(asset=_toSell)["free"])
        _quantity =  round(_balance/_price,5) - 0.00002 #round and than subtract to avoid rounding to value higher than balance
        print _quantity
        print _balance/_price
        order = client.create_test_order(
            symbol = _pair,
            side = "BUY",
            type = "LIMIT",
            timeInForce = "GTC",
            quantity = _quantity,
            price = _price
예제 #25
0
holdings = {}

streams = map(lambda s: s.lower() + "usdt@kline_1m", coins)
endpoint = "/".join(streams)

SOCKET = "wss://stream.binance.com:9443/ws/" + endpoint

opens = {c: [] for c in coins}
closes = {c: [] for c in coins}
rates = {c: [] for c in coins}
prices = {c: 0 for c in coins}

last_msg = "none yet"
channel = -1  # should start with a default channel but I'm lazy

binance_client = Client(config.API_KEY, config.API_SECRET, tld='us')
discord_client = discord.Client()


#########################################################################################################
# Helpers
#########################################################################################################
# truncates the given float to N decimal places, returned as a float (typically used for quantities)
def xf(coin, value):
    p = precisions.get(coin, 1.0)
    return int(value * p) / p


# truncates the given float to 3 decimal places, returned as a string (typically used for prices)
def xs(value):
    return "{}".format(int(value * 1000) / 1000.0)
 def __init__(self):
     with open('../metadata/binance_keys.txt') as f:
         keys = f.read()
         keys = keys.split(',')
         PriceMoves.API, PriceMoves.API_SECRET = keys[0], keys[1]
     self.client = Client(PriceMoves.API, PriceMoves.API_SECRET)
예제 #27
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
'''


def get_api(filename):
    try:
        with open(filename, 'r') as api_key:
            return eval(api_key.read())
    except Exception as e:
        print e
        print 'Write the keys in string formats. For eg: ["fjkdslfdslfds"]'


keys = get_api('api_key.txt')

client = Client(keys[0], keys[1])
'''
Getting the token names that we wish to trade
'''

with open('Tokens.dat', 'r') as tokens:
    mess1 = tokens.read()
    scrips = eval(mess1)

# Extracting Valid Tokens
total_traded_tokens = [i['symbol'] for i in client.get_all_tickers()]

valid_tokens = [i for i in scrips if i in total_traded_tokens]
'''
Lets define a small function that will extract tokens from pairs. This we want to know our indiviudal token names
to get their respective balances.
예제 #29
0
from merkato.exchanges.kraken_exchange.constants import DEPTH, ADD_ORDER, RESULT, OPEN_ORDERS, REF_ID, DESCRIPTION, CANCEL_ORDER, TICKER, TRADES_HISTORY, QUERY_ORDERS, \
    CRYPTO_ASSETS, TRADES, OPEN, VOL, VOLUME_EXECUTED

from math import floor
import sqlite3

from binance.enums import *
from binance.client import Client
from binance.enums import *
import krakenex

client = Client()

base_balance = client.get_asset_balance(asset='BTC', recvWindow=10000000)
coin_balance = client.get_asset_balance(asset='XMR', recvWindow=10000000)
history = client.get_my_trades(symbol='XMRBTC',
                               recvWindow=10000000,
                               fromId=5419788)
history_2 = client.get_my_trades(symbol='XMRBTC',
                                 recvWindow=10000000,
                                 fromId=7294366)
# history_3 = client.get_my_trades(symbol='XMRBTC', recvWindow=10000000, fromId=9113531)
# print('history', history_3[0], history_3[len(history_3)-1])
history += history_2
date_obj = {
    'sep': {
        'btc': 0,
        'xmr': 0
    },
    'oct': {
        'btc': 0,
def get_historical_klines(symbol, interval, start_str, end_str=None):
    """Get Historical Klines from Binance
    See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/
    If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
    :param symbol: Name of symbol pair e.g BNBBTC
    :type symbol: str
    :param interval: Biannce Kline interval
    :type interval: str
    :param start_str: Start date string in UTC format
    :type start_str: str
    :param end_str: optional - end date string in UTC format
    :type end_str: str
    :return: list of OHLCV values
    """
    # create the Binance client, no need for api key
    client = Client("", "")

    # init our list
    output_data = []

    # setup the max limit
    limit = 500

    # convert interval to useful value in seconds
    timeframe = interval_to_milliseconds(interval)

    # convert our date strings to milliseconds
    start_ts = date_to_milliseconds(start_str)

    # if an end time was passed convert it
    end_ts = None
    if end_str:
        end_ts = date_to_milliseconds(end_str)

    idx = 0
    # it can be difficult to know when a symbol was listed on Binance so allow start time to be before list date
    symbol_existed = False
    while True:
        # fetch the klines from start_ts up to max 500 entries or the end_ts if set
        temp_data = client.get_klines(
            symbol=symbol,
            interval=interval,
            limit=limit,
            startTime=start_ts,
            endTime=end_ts
        )
        print(temp_data)
        # handle the case where our start date is before the symbol pair listed on Binance
        if not symbol_existed and len(temp_data):
            symbol_existed = True

        if symbol_existed:
            # append this loops data to our output data
            output_data += temp_data

            # update our start timestamp using the last value in the array and add the interval timeframe
            start_ts = temp_data[len(temp_data) - 1][0] + timeframe
        else:
            # it wasn't listed yet, increment our start date
            start_ts += timeframe

        idx += 1
        # check if we received less than the required limit and exit the loop
        if len(temp_data) < limit:
            # exit the while loop
            break

        # sleep after every 3rd call to be kind to the API
        if idx % 3 == 0:
            time.sleep(1)

    return output_data