Exemplo n.º 1
0
class FtGet:
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)
        self.symbol = 'ftusdt'
        self.now_balance = None
        self.buy_balance = None

    ## 获取最新成交价
    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)
        now_price = ticker['data']['ticker'][0]
        print('最新成交价', now_price)
        return now_price

    def process(self):
        pass

    def loop(self):
        while True:
            try:
                self.process()
            except:
                print('err')
            time.sleep(5)
Exemplo n.º 2
0
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)
        self.log = Log("")
        self.symbol = 'ftusdt'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.count_flag = 0
        self.fall_rise = 0
        self.buy_price = 0.0
        # 正在卖出
        self.in_sell = False
        # 卖出价格
        self.sell_price = 0.0
        # 价格队列
        self.price_queue = []
        # 验证是否卖出价格
        self.check_sell_price = 0.0
        # 总共的增量
        self.total_increment = 0.0
        # 服务器时间
        self.diff_server_time = None

        stategy_quick.set_app(self)
        candle_data.set_app(self)
Exemplo n.º 3
0
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)

        self.symbol = 'ethusdt'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
Exemplo n.º 4
0
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)

        self.symbol = 'ftusdt'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = self.digits(self.get_ticker(), 6)
Exemplo n.º 5
0
 def __init__(self):
     self.fcoin = Fcoin()
     self.fcoin.auth(config.api_key, config.api_secret)
     self.symbol = config.socket+config.blc
     self.order_id = None
     self.dic_balance = defaultdict(lambda: None)
     self.time_order = time.time()
     self.oldprice = self.get_prices()
     self.socket_sxf=0.0
     self.blc_sxf=0.0
     self.begin_balance=self.get_blance()
Exemplo n.º 6
0
 def __init__(self):
     self.fcoin = Fcoin()
     self.fcoin.auth(config.api_key, config.api_secret)
     self.log = Log("coin")
     self.symbol = 'ftusdt'
     self.order_id = None
     self.dic_balance = defaultdict(lambda: None)
     self.time_order = time.time()
     self.oldprice = [self.digits(self.get_ticker(),6)]
     self.now_price = 0.0
     self.type = 0
     self.fee = 0.0
     self.begin_balance=self.get_blance()
Exemplo n.º 7
0
    def __init__(self):
        # initialize the Fcoin API
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)

        self.symbol = 'fteth'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = [self.digits(self.get_ticker(), 6)]
        # don't quite know what are these
        self.eth_sxf = 0.0
        self.ft_sxf = 0.0
        self.begin_balance = self.get_balance()
Exemplo n.º 8
0
 def __init__(self):
     self.fcoin = Fcoin()
     self.fcoin.auth(config.api_key, config.api_secret)
     self.log = Log("")
     self.symbol = 'ftusdt'
     self.order_id = None
     self.dic_balance = defaultdict(lambda: None)
     self.now_price = 0.0
     self.type = 0
     self.fee = 0.0
     self.count_flag = 0
     self.fall_rise = 0
     self.buy_price =0.0
     self.sell_price = 0.0
Exemplo n.º 9
0
 def __init__(self):
     self.fcoin = Fcoin()
     self.fcoin.auth(config.api_key, config.api_secret)
     self.log = Log("")
     self.symbol = 'ftusdt'
     self.order_id = None
     self.dic_balance = defaultdict(lambda: None)
     self.time_order = time.time()
     self.oldprice = self.digits(self.get_ticker(), 6)
     self.now_price = 0.0
     self.type = 0
     self.fee = 0.0
     self.count_flag = 0
     self.fall_rise = 0
     self.buy_price = 0.0
     self.sell_price = 0.0
     self.executor = ThreadPoolExecutor(max_workers=4)
Exemplo n.º 10
0
class Fteth():
    def __init__(self):
        # initialize the Fcoin API
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)

        self.symbol = 'fteth'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = [self.digits(self.get_ticker(), 6)]
        # don't quite know what are these
        self.eth_sxf = 0.0
        self.ft_sxf = 0.0
        self.begin_balance = self.get_balance()

    def digits(self, num, digit):
        '''
        Get rid of decimals after number of [num] digits
        '''
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)
        current_price = ticker['data']['ticker'][0]
        print('new trade price: ', current_price)
        return current_price

    def get_balance(self):
        dic_balance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        if data:
            for item in data['data']:
                dic_balance[item['currency']] = balance(
                    float(item['available']), float(item['frozen']),
                    float(item['balance']))
        return dic_balance

    def process(self):
        price = self.digits(self.get_ticker(), 8)

        self.oldprice.append(price)
        self.dic_balance = self.get_balance()
        ft = self.dic_balance['ft']
        eth = self.dic_balance['eth']

        order_list = self.fcoin.list_orders(symbol=self.symbol,
                                            states='submitted')['data']

        if not order_list or len(order_list) < 2:
            # make sure we will make profit from this
            # check eth balance and current price
            if eth and abs(price / self.oldprice[len(self.oldprice) - 2] -
                           1) < 0.02:
                # if the price is above the average of 2 latest prices

                if price * 2 > self.oldprice[len(self.oldprice) -
                                             2] + self.oldprice[
                                                 len(self.oldprice) - 3]:
                    # calculate amount to buy
                    amount = self.digits(ft.available * 0.25, 2)

                    if amount > 5:
                        # but some FT
                        data = self.fcoin.buy(self.symbol, price, amount)
                        # if the trade is success
                        if data:
                            self.ft_sxf += amount * 0.001
                            self.order_id = data['data']
                            self.time_order = time.time()
                    else:
                        if float(ft.available) * 0.25 > 5:
                            # use 25 precentage
                            amount = self.digits()
                            data = self.fcoin.sell(self.symbol, price, amount)
                            if data:
                                # record transaction fee
                                self.eth_sxf += amount * price * 0.001
                                # record time
                                self.time_order = time.time()
                                #
                                self.order_id = data['data']
                                print('sell success')
                else:
                    print('error')
            else:
                print('system busy')
                if len(order_list) >= 1:
                    data = self.fcoin.cancel_order(order_list[len(order_list) -
                                                              1]['id'])
                    print(order_list[len(order_list) - 1])
                    if data:
                        if order_list[len(order_list) -
                                      1]['side'] == 'buy' and order_list[
                                          len(order_list) -
                                          1]['symbol'] == 'fteth':
                            self.ft_sxf -= float(
                                order_list[len(order_list) -
                                           1]['amount']) * 0.001
                        elif order_list[len(order_list) -
                                        1]['side'] == 'sell' and order_list[
                                            len(order_list) -
                                            1]['symbol'] == 'fteth':
                            self.eth_sxf -= float(
                                order_list[len(order_list) -
                                           1]['amount']) * float(
                                               order_list[len(order_list) -
                                                          1]['price']) * 0.001

    def loop(self):
        while True:
            try:
                self.process()
                print('success')
            except:
                print('err')
            time.sleep(5)
sys.path.append("../fcoin-python-sdk")
sys.path.append("../common_python")
#print(sys.path)

from fcoin3 import Fcoin  #if python3 use fcoin3 → from fcoin3 import Fcoin
from common import Common

file_name = "../keys.csv"

common = Common()
token = common.get_csv_val_by_key(file_name, "line_token")
common.set_line_token(token)

# In[55]:

fcoin = Fcoin()

data = pd.DataFrame(fcoin.get_market_ticker("btcusdt"))
latest_price = data.at["ticker", "data"][0]
print(latest_price)
common.line_notify("BTC/USDT 最新価格: " + str(latest_price))

#print(fcoin.get_symbols())

#print(fcoin.get_currencies())

#fcoin.auth('you-key', 'you-secret')

#print(fcoin.get_balance())

#print(fcoin.buy('fteth', 0.0001, 10))
Exemplo n.º 12
0
#coding:utf-8
from fcoin3 import Fcoin
from Logging import Logger
import time
import json
import sys
import traceback
import math
import config

fcoin = Fcoin()
fcoin.auth(config.key, config.secret)  # 授权

# 写日志
log = Logger('all.log', level='debug')

# 例子
# log.logger.debug('debug')
# log.logger.info('info')
# log.logger.warning('警告')
# log.logger.error('报错')
# log.logger.critical('严重')


#平价买卖
def get_ticket1():
    r = fcoin.get_market_ticker(config.symbol['name'])
    num = (r['data']['ticker'][2] + r['data']['ticker'][4]) / 2.0
    return pricedecimal(num)  #精度控制

Exemplo n.º 13
0
# -*- coding: utf-8 -*-
from fcoin3 import Fcoin
from websocket import create_connection
import time
import sys
import datetime
import _thread
import gzip

fcoin = Fcoin()
ApiKey = ''
SecretKey = ''
#ApiKey='d6737fdb557a406f86d394ed59e1deee'
#SecretKey='e8387b34c2c84f00b1c052812e0d1188'

#------------------modify these parameters if you changed the coin type--------------
precision = 6  # price decimal
quantPrecision = 2  # quantity decimal
buy_sell_quantities_base = 5  # amount for each trading
quantityFactor = 1  # the more stable the price, the more quantity for trading.  Normally set to 2. If do not use it, set to 1.
trade_paire = "ftusdt"
oscillation1 = 0.0002  # aceptable price oscillation
oscillation2 = oscillation1 * 2  # aceptable price oscillation
oscillation3 = oscillation1 * 4  # aceptable price oscillation
reTrade_loss = 0.0002  # basic acceptable loss rate, for zero benifit.
force_trade_lost = oscillation3  # accept more loss when force trade is needed.
modifier_buy = 1.00003  # higher price to buy
modifier_sell = 0.99997  # lower price to sell
#------------------------------------------------------------------------------------

#total_count = 5     # maximum number of trades
Exemplo n.º 14
0
class app():
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)

        self.symbol = 'ftusdt'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = self.digits(self.get_ticker(), 6)

    def digits(self, num, digit):
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)
        now_price = ticker['data']['ticker'][0]
        print('最新成交价', now_price)
        return now_price

    def get_blance(self):
        dic_blance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        print(data)
        if data:
            for item in data['data']:
                dic_blance[item['currency']] = balance(
                    float(item['available']), float(item['frozen']),
                    float(item['balance']))
        return dic_blance

    def process(self):
        self.dic_balance = self.get_blance()

        ft = self.dic_balance['ft']

        usdt = self.dic_balance['usdt']
        print('usdt  has ....', usdt.available, 'ft has ...', ft.available)
        price = self.digits(self.get_ticker(), 6)

        order_list = self.fcoin.list_orders(symbol=self.symbol,
                                            states='submitted')['data']

        print('order list', order_list)
        if not order_list or len(order_list) < 3:
            if usdt and abs(price / self.oldprice - 1) < 0.02:
                if price > self.oldprice:
                    amount = self.digits(usdt.available / price * 0.25, 2)
                    if amount > 5:
                        data = self.fcoin.buy(self.symbol, price, amount)
                        if data:
                            print('buy success', data)
                            self.order_id = data['data']
                            self.time_order = time.time()
                else:
                    if float(ft.available) * 0.25 > 5:
                        amount = self.digits(ft.available * 0.25, 2)
                        data = self.fcoin.sell(self.symbol, price, amount)
                        if data:
                            self.time_order = time.time()
                            self.order_id = data['data']
                            print('sell success')
            else:
                print('error')
        else:
            print('system busy')
            order_list = self.fcoin.list_orders(symbol=self.symbol,
                                                states='submitted')['data']
            if len(order_list) >= 1:
                self.fcoin.cancel_order(order_list[0]['id'])
        self.oldprice = price

    def loop(self):
        while True:
            try:
                self.process()
                print('succes')
            except:
                print('err')
            time.sleep(1)
Exemplo n.º 15
0
logger.setLevel(level=logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(asctime)s] %(message)s')
handler = logging.FileHandler("btc_%s.txt" % time.strftime("%Y-%m-%d %H-%M-%S"))
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
logger.addHandler(console)
logger.addHandler(handler)

f = open('accounts.txt')
lines = f.readlines()
acct_id = int(lines[-1])
api_key = lines[acct_id*2 - 2].strip('\n')
seceret_key = lines[acct_id*2 - 1].strip('\n')
fcoin = Fcoin()
fcoin.auth(api_key, seceret_key)  # fcoin.margin_buy('ethusdt', 0.01, 10)
ex0 = ccxt.fcoin()
ex1 = ccxt.okex3()
ex2 = ccxt.binance()
ex3 = ccxt.huobipro()
type = 'limit'
trend = 0 
trend_0, trend_1, trend_2, trend_3, trend_cmb = [], [], [], [], []
pre_price_0 = 0
pre_price_1, score_1 = 0, 0
pre_price_2, score_2 = 0, 0
pre_price_3, score_3 = 0, 0
pre_price_4, score_4 = 0, 0
pre_price_5, score_5 = 0, 0
pre_price_cmb, score_cmb = 0, 0
Exemplo n.º 16
0
 def __init__(self):
     self.fcoin = Fcoin()
     self.fcoin.auth(config.api_key, config.api_secret)
     self.symbol = 'ftusdt'
     self.now_balance = None
     self.buy_balance = None
Exemplo n.º 17
0
class app():
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)
        self.symbol = config.socket+config.blc
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = self.get_prices()
        self.socket_sxf=0.0
        self.blc_sxf=0.0
        self.begin_balance=self.get_blance()
        
    def get_prices(self):
        i=2
        prices=[]
        while i>0:
           prices.append(self.digits(self.get_ticker(),6))
           i-=1
           time.sleep(1)
        return prices

    def digits(self, num, digit):
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)
        now_price = ticker['data']['ticker'][0]
        print('最新成交价', now_price)
        return now_price

    def get_blance(self):
        dic_blance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        if data:
            for item in data['data']:
                dic_blance[item['currency']] = balance(float(item['available']), float(item['frozen']),float(item['balance']))
        return dic_blance

    def process(self):
        price = self.digits(self.get_ticker(),6)
        
        self.oldprice.append(price)
        
        p1=self.oldprice[len(self.oldprice)-2]
        p2=self.oldprice[len(self.oldprice)-3]
        
        self.dic_balance = self.get_blance()

        socket = self.dic_balance[config.socket]

        blc = self.dic_balance[config.blc]  
        
        print(config.blc+'_now  has ....', blc.balance, config.socket+'_now has ...', socket.balance)
        print(config.blc+'_sxf  has ....', self.blc_sxf, config.socket+'_sxf has ...', self.socket_sxf)
        print(config.blc+'_begin  has ....', self.begin_balance[config.blc].balance, config.socket+'_begin has ...', self.begin_balance[config.socket].balance)
        print(config.blc+'_all_now  has ....', blc.balance+self.blc_sxf, config.socket+'_all_now has ...', socket.balance+self.socket_sxf)

        order_list = self.fcoin.list_orders(symbol=self.symbol,states='submitted')['data'] 

        if not order_list or len(order_list) < 2:
            if blc and abs(price/self.oldprice[len(self.oldprice)-2]-1)<0.02:
                if price*2>p1+p2:
                    amount = self.digits(blc.available / price * 0.25, 2)
                    if amount > 5:
                        data = self.fcoin.buy(self.symbol, price, amount)
                        if data:
                            print('buy success',data)
                            self.socket_sxf += amount*0.001
                            self.order_id = data['data']
                            self.time_order = time.time()
                else:
                    if  float(socket.available) * 0.25 > 5:
                        amount = self.digits(socket.available * 0.25, 2)
                        data = self.fcoin.sell(self.symbol, price, amount)
                        if data:
                            self.blc_sxf += amount*price*0.001
                            self.time_order = time.time()
                            self.order_id = data['data']
                            print('sell success')
            else:
                print('error')
        else:
            print('system busy')
            if len(order_list) >= 1:
                data=self.fcoin.cancel_order(order_list[len(order_list)-1]['id'])
                print(order_list[len(order_list)-1])
                if data:
                    if order_list[len(order_list)-1]['side'] == 'buy' and order_list[len(order_list)-1]['symbol'] == self.symbol:
                        self.socket._sxf -= float(order_list[len(order_list)-1]['amount'])*0.001
                    elif order_list[len(order_list)-1]['side'] == 'sell' and order_list[len(order_list)-1]['symbol'] == self.symbol:
                        self.blc_sxf -= float(order_list[len(order_list)-1]['amount'])*float(order_list[len(order_list)-1]['price'])*0.001
        
        

    def loop(self):
        while True:
            try:
                self.process()
                print('succes')
            except:
                print('err')
            time.sleep(5)
Exemplo n.º 18
0
class app():
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)

        self.symbol = 'ftusdt'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = [self.digits(self.get_ticker(), 6)]
        self.usdt_sxf = 0.0
        self.ft_sxf = 0.0
        self.begin_balance = self.get_blance()

    def digits(self, num, digit):
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)
        now_price = ticker['data']['ticker'][0]
        print('最新成交价', now_price)
        return now_price

    def get_blance(self):
        dic_blance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        if data:
            for item in data['data']:
                dic_blance[item['currency']] = balance(
                    float(item['available']), float(item['frozen']),
                    float(item['balance']))
        return dic_blance

    def process(self):
        price = self.digits(self.get_ticker(), 6)

        self.oldprice.append(price)

        self.dic_balance = self.get_blance()

        ft = self.dic_balance['ft']

        usdt = self.dic_balance['usdt']

        print('usdt_now  has ....', usdt.balance, 'ft_now has ...', ft.balance)
        print('usdt_sxf  has ....', self.usdt_sxf, 'ft_sxf has ...',
              self.ft_sxf)
        print('usdt_begin  has ....', self.begin_balance['usdt'].balance,
              'ft_begin has ...', self.begin_balance['ft'].balance)
        print('usdt_all_now  has ....', usdt.balance + self.usdt_sxf,
              'ft_all_now has ...', ft.balance + self.ft_sxf)

        order_list = self.fcoin.list_orders(symbol=self.symbol,
                                            states='submitted')['data']

        if not order_list or len(order_list) < 2:
            # make sure it is still profitable
            # if usdt balance is bigger than zero and
            # the current price is within 2% fluctuation compared to the latest old price
            if usdt and abs(price / self.oldprice[len(self.oldprice) - 2] -
                            1) < 0.02:
                # if the price is above the average of 2 latest prices
                if price * 2 > self.oldprice[len(self.oldprice) -
                                             2] + self.oldprice[
                                                 len(self.oldprice) - 3]:
                    # set the amount for buying using 25% of remaining usdt
                    amount = self.digits(usdt.available / price * 0.25, 2)
                    # if amount is bigger than 5
                    if amount > 5:
                        # buy it
                        data = self.fcoin.buy(self.symbol, price, amount)
                        if data:
                            print('buy success', data)
                            self.ft_sxf += amount * 0.001
                            self.order_id = data['data']
                            self.time_order = time.time()
                else:
                    # if the price is not bigger than the average which means the price is dropping
                    if float(ft.available) * 0.25 > 5:
                        # sell 25 precent of fts we are holding
                        amount = self.digits(ft.available * 0.25, 2)
                        data = self.fcoin.sell(self.symbol, price, amount)
                        if data:
                            # record transaction fee
                            self.usdt_sxf += amount * price * 0.001
                            # record time
                            self.time_order = time.time()
                            #
                            self.order_id = data['data']
                            print('sell success')
            else:
                print('error')

        else:
            print('system busy')
            if len(order_list) >= 1:
                data = self.fcoin.cancel_order(order_list[len(order_list) -
                                                          1]['id'])
                print(order_list[len(order_list) - 1])
                if data:
                    if order_list[len(order_list) -
                                  1]['side'] == 'buy' and order_list[
                                      len(order_list) -
                                      1]['symbol'] == 'ftusdt':
                        self.ft_sxf -= float(
                            order_list[len(order_list) - 1]['amount']) * 0.001
                    elif order_list[len(order_list) -
                                    1]['side'] == 'sell' and order_list[
                                        len(order_list) -
                                        1]['symbol'] == 'ftusdt':
                        self.usdt_sxf -= float(
                            order_list[len(order_list) - 1]['amount']) * float(
                                order_list[len(order_list) -
                                           1]['price']) * 0.001

    def loop(self):
        while True:
            try:
                self.process()
                print('succes')
            except:
                print('err')
            time.sleep(5)
Exemplo n.º 19
0
from fcoin3 import Fcoin
import os

fcoin = Fcoin()

print(fcoin.get_symbols())

print(fcoin.get_currencies())

api_key = os.environ["FCOIN_API_KEY"]
api_sec = os.environ["FCOIN_API_SECRET"]

fcoin.auth(api_key, api_sec)

print(fcoin.get_balance())

print(fcoin.buy('fteth', 0.0001, 10))
#print(fcoin.sell('fteth', 0.002, 5))
#print(fcoin.cancel_order('6TfBZ-eORp4_2nO5ar6zhg0gLLvuWzTTmL1OzOy9OYg='))
#print(fcoin.get_candle('M1','fteth'))
Exemplo n.º 20
0
UL_FCOIN = 10000
LL_FCOIN = 3000

USE_BITBANK = True
TICKER_BITBANK = 'XRP/JPY'
UL_BITBANK = 100
LL_BITBANK = 10

USE_KABU = False
TICKER_KABU = '6503'
UL_KABU = 2000
LL_KABU = 500

# ---- Fcoinからのデータ取得&通知 ----
if USE_FCOIN:
    fcoin = Fcoin()
    data = pd.DataFrame(fcoin.get_market_ticker(TICKER_FCOIN))
    latest_price = data.at["ticker", "data"][0]
    common.send_message(TICKER_FCOIN + ":" + str(latest_price))

    if latest_price > UL_FCOIN:
        text = "【FCOIN】"
        text += TICKER_FCOIN + ":" + str(latest_price) + " が "
        text += str(UL_FCOIN) + " を超えました!売りタイミングです!" + '\n'
        text += "( ^ω^)"
        common.send_message(text)
    elif latest_price < LL_FCOIN:
        text = "【FCOIN】"
        text += TICKER_FCOIN + ":" + str(latest_price) + " が "
        text += str(UL_FCOIN) + " を下回りました…損切タイミングです…" + '\n'
        common.send_message(text)
Exemplo n.º 21
0
from fcoin3 import Fcoin
from log import Log
import time
import sys
import threadpool
import config

UsdtMin = 38000
Amount = 100

fcoin = Fcoin()
fcoin.auth(config.get_public_key(), config.get_private_key())

pool = threadpool.ThreadPool(2)
log = Log()

def getUsdt(): 
    balance = fcoin.get_balance()
    data = balance['data']
    for item in data:
        if item['currency'] == 'usdt':
            return float(item['balance'])
    return 0

def getAvaiCoin(token):
    balance = fcoin.get_balance()
    data = balance['data']
    for item in data:
        if item['currency'] == token:
            return float(item['available'])
    return 0
Exemplo n.º 22
0
from fcoin3 import Fcoin
import time
import json
from decimal import Decimal

with open("quz.json", 'r') as load_f:
    load_dict = json.load(load_f)
    print(load_dict)
api_key = load_dict['api_key']
secret_key = load_dict['secret_key']
buy_depth = load_dict['buy_depth']
sell_depth = load_dict['sell_depth']
symbol = load_dict['symbol']
fcoin = Fcoin()
fcoin.auth(api_key, secret_key)
base_currency = ""
quote_currency = ""
price_decimal = 0
amount_decimal = 0

symbols = fcoin.get_symbols()
print(symbol)
for s in symbols:
    if s['name'] == symbol:
        base_currency = s['base_currency']
        quote_currency = s['quote_currency']
        price_decimal = s['price_decimal']
        amount_decimal = s['amount_decimal']
        break
min_price_diff = Decimal(pow(10, -price_decimal))
Exemplo n.º 23
0
filled = 'filled'
# 已提交(未成交)
submitted = 'submitted'
# 买金额
buy_amount = Config['buy_amount']
# 卖金额
sell_amount = Config['sell_amount']
# 交易对
symbol = Config['symbol']
#止盈
zhiying = Config['zhiying']
#止损
zhisun = Config['zhisun']

# 初始化
fcoin = Fcoin()

# 授权
api_key = Api['key']
api_secret = Api['secret']
fcoin.auth(api_key, api_secret)


# 获取交易对的筹码类型
def get_symbol_type(this_symbol):
    types = dict(ftusdt='ft',
                 btcusdt='btc',
                 ethusdt='eth',
                 bchusdt='bch',
                 ltcusdt='ltc',
                 etcusdt='etc')
Exemplo n.º 24
0
class App():
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)
        self.log = Log("")
        self.symbol = 'ftusdt'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = self.digits(self.get_ticker(), 6)
        self.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.count_flag = 0
        self.fall_rise = 0
        self.buy_price = 0.0
        self.sell_price = 0.0
        self.executor = ThreadPoolExecutor(max_workers=4)

    def digits(self, num, digit):
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)['data']['ticker']
        self.now_price = ticker[0]
        self.buy_price = ticker[2]
        self.sell_price = ticker[4]
        return self.now_price

    def get_must_sell_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)['data']['ticker']
        self.now_price = ticker[0]
        self.buy_price = ticker[2]
        self.sell_price = ticker[4]
        return self.buy_price

    def get_must_buy_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)['data']['ticker']
        self.now_price = ticker[0]
        self.buy_price = ticker[2]
        self.sell_price = ticker[4]
        return self.sell_price

    def get_blance(self):
        dic_blance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        if data:
            for item in data['data']:
                dic_blance[item['currency']] = balance(
                    float(item['available']), float(item['frozen']),
                    float(item['balance']))
        return dic_blance

    def syn_blance(self):
        dic_blance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        if data:
            for item in data['data']:
                dic_blance[item['currency']] = balance(
                    float(item['available']), float(item['frozen']),
                    float(item['balance']))

        return dic_blance

    def save_csv(self, array):
        with open("data/trade.csv", "a+", newline='') as w:
            writer = csv.writer(w)
            writer.writerow(array)

    def reset_save_attrubute(self):
        self.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.order_id = None

    def jump(self):
        self.dic_balance = self.get_blance()
        ft = self.dic_balance["ft"]
        usdt = self.dic_balance["usdt"]
        if usdt.available > 10:
            price = self.digits(self.get_must_buy_ticker(), 6)
            amount = self.digits(usdt.available / price * 0.99, 2)
            if amount >= 5:
                data = self.fcoin.buy(self.symbol, price, amount, 'market')
                if data:
                    self.fee = amount * 0.001
                    self.order_id = data['data']
                    self.time_order = time.time()
                    self.type = 1
                    self.log.info(
                        'buy success price--[%s] amout--[%s] fee--[%s]' %
                        (price, amount, self.fee))

                    time.sleep(270)

                    self.dic_balance = self.get_blance()
                    ft = self.dic_balance["ft"]
                    usdt = self.dic_balance["usdt"]

                    new_price = price
                    while new_price <= price:
                        new_price = self.digits(self.get_must_sell_ticker(),
                                                amount)
                        time.sleep(5)

                    if new_price > price:
                        data = self.fcoin.sell(self.symbol, price, amount,
                                               'market')
                        self.log.info(
                            'sell success price--[%s] amout--[%s] fee--[%s]' %
                            (price, amount, self.fee))
Exemplo n.º 25
0
class App():
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)
        self.log = Log("")
        self.symbol = 'ftusdt'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.count_flag = 0
        self.fall_rise = 0
        self.buy_price =0.0
        self.sell_price = 0.0

    def digits(self, num, digit):
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)['data']['ticker']
        self.now_price = ticker[0]
        self.buy_price = ticker[2]
        self.sell_price = ticker[4]
        return self.now_price

    def get_must_sell_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)['data']['ticker']
        self.now_price = ticker[0]
        self.buy_price = ticker[2]
        self.sell_price = ticker[4]
        return self.buy_price

    def get_must_buy_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)['data']['ticker']
        self.now_price = ticker[0]
        self.buy_price = ticker[2]
        self.sell_price = ticker[4]
        return self.sell_price

    def get_blance(self):
        dic_blance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        if data:
            for item in data['data']:
                dic_blance[item['currency']] = balance(float(item['available']), float(item['frozen']),float(item['balance']))
        return dic_blance

    def save_csv(self,array):
        with open("data/trade.csv","a+",newline='') as w:
            writer = csv.writer(w)
            writer.writerow(array)

    def reset_save_attrubute(self):
        self.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.order_id = None
    
    def server_time(self):
        now = datetime.datetime.fromtimestamp(int(self.fcoin.get_server_time()/1000))
        return now

    def dateDiffInSeconds(self, date1, date2):
        timedelta = date2 - date1
        return timedelta.days*24*3600 + timedelta.seconds
        
    def do_hour(self):
        self.dic_balance = self.get_blance()
        ft = self.dic_balance["ft"]
        usdt = self.dic_balance["usdt"]
        print('ft:%s usdt:%s' % (ft.available,usdt.available))

        if usdt.available > 10:
            price = self.digits(self.get_must_buy_ticker(),6)
            amount = self.digits(usdt.available / price * 0.98, 2)
            if amount >= 5:
                self.log.info('buy price--[%s] amout--[%s]' % (price,amount))
                data = self.fcoin.buy(self.symbol, price, amount, 'limit')
                if data:
                    self.order_id = data['data']
                    self.log.info('buy order success price--[%s] amout--[%s]' % (price,amount))

                    server_time = self.server_time()
                    start_time = server_time.replace(minute=58, second=50,microsecond=0)
                    sleep_seconds = self.dateDiffInSeconds(server_time, start_time)
                    if sleep_seconds > 1:
                        time.sleep(sleep_seconds)
                    
                    self.dic_balance = self.get_blance()
                    ft = self.dic_balance["ft"]
                    usdt = self.dic_balance["usdt"]
                    
                    new_price = price
                    while new_price <= price:
                        new_price = self.digits(self.get_must_sell_ticker(),6)
                        time.sleep(5)

                    if new_price > price:
                        self.log.info('sell price--[%s] amout--[%s]' % (price,amount))
                        data = self.fcoin.sell(self.symbol, new_price, amount,'limit')
                        self.log.info('sell order success price--[%s] amout--[%s]' % (new_price, amount))


    def loop(self):
        while True:
            try:
                server_time = self.server_time()
                start_time = server_time.replace(minute=50, second=0,microsecond=0)
                sleep_seconds = self.dateDiffInSeconds(server_time, start_time)
                if sleep_seconds > 1:
                    print("servertime: %s , starttime: %s , sleep: %s" % (server_time,start_time,sleep_seconds))
                    time.sleep(sleep_seconds)
                    self.do_hour()
                else:
                    time.sleep(60)

            except Exception as e:
                self.log.info(e)
                print(e)
            finally:
                self.reset_save_attrubute()
Exemplo n.º 26
0
class App():
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)
        self.log = Log("coin")
        self.symbol = 'ftusdt'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = [self.digits(self.get_ticker(),6)]
        self.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.begin_balance=self.get_blance()

    def digits(self, num, digit):
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)
        self.now_price = ticker['data']['ticker'][0]
        self.log.info("now price%s" % self.now_price )
        return self.now_price

    def get_blance(self):
        dic_blance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        if data:
            for item in data['data']:
                dic_blance[item['currency']] = balance(float(item['available']), float(item['frozen']),float(item['balance']))
        return dic_blance

    def save_csv(self,array):
        with open("data/trade.csv","a+",newline='') as w:
            writer = csv.writer(w)
            writer.writerow(array)

    def reset_save_attrubute(self):
        self.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.order_id = None

    def process(self):
        price = self.digits(self.get_ticker(),6)
        self.oldprice.append(price)
        self.dic_balance = self.get_blance()

        ft = self.dic_balance['ft']
        usdt = self.dic_balance['usdt']
        
        self.log.info("usdt has--[%s]   ft has--[%s]" % (usdt.balance, ft.balance))

        order_list = self.fcoin.list_orders(symbol=self.symbol,states='submitted')['data']
        print(order_list)
        self.log.info("order trading: %s" % order_list)

        if not order_list or len(order_list) < 2:
            if usdt and abs(price/self.oldprice[len(self.oldprice)-2]-1)<0.02:
                if price*2 < self.oldprice[len(self.oldprice)-2]+self.oldprice[len(self.oldprice)-3]:
                    amount = self.digits(usdt.available / price * 0.25, 2)
                    if amount > 5:
                        data = self.fcoin.buy(self.symbol, price, amount)
                        if data:
                            self.fee = amount*0.001
                            self.order_id = data['data']
                            self.time_order = time.time()
                            self.type = 1
                            self.log.info('buy success price--[%s] amout--[%s] fee--[%s]' % (price,amount ,self.fee))
                else:
                    if float(ft.available) * 0.25 > 5:
                        amount = self.digits(ft.available * 0.25, 2)
                        data = self.fcoin.sell(self.symbol, price, amount)
                        if data:
                            self.fee = amount*price*0.001
                            self.time_order = time.time()
                            self.order_id = data['data']
                            self.type = 2
                            self.log.info("sell success price--[%s] amout--[%s] fee--[%s]" % (price,amount, self.fee))

            else:
                print('价格波动过大 %s' % usdt)
                self.log.info("价格波动过大%s" % usdt)
        else:
            print('system busy')
            if len(order_list) >= 1:
                self.log.info("cancel order {%s}" % order_list[-1])
                order_id = order_list[-1]['id']
                data = self.fcoin.cancel_order(order_id)
                self.log.info("cancel result {%s}" % data)
                if data:
                    if order_list[len(order_list)-1]['side'] == 'buy' and order_list[len(order_list)-1]['symbol'] == 'ftusdt':
                        self.fee = -float(order_list[len(order_list)-1]['amount'])*0.001
                    elif order_list[len(order_list)-1]['side'] == 'sell' and order_list[len(order_list)-1]['symbol'] == 'ftusdt':
                        self.fee = -float(order_list[len(order_list)-1]['amount'])*float(order_list[len(order_list)-1]['price'])*0.001
                    self.type = 3
                    self.order_id = order_id
        
    def loop(self):
        while True:
            try:
                time1 = time.time()
                self.process()
                array = [self.order_id,self.now_price,self.type,self.fee,self.symbol,time.strftime('%Y-%m-%d %H:%M:%S')]
                if type != 0:
                    self.save_csv(array)
                self.log.info("--------success-------")
                time2 = time.time()
                self.log.info("app time--%s"% str(time2-time1))
                time.sleep(3)
            except Exception as e:
                self.log.info(e)
                print(e)
            finally:
                self.reset_save_attrubute()
Exemplo n.º 27
0
    omg_balance, eth_balance = get_balance(fcoin=fcoin)
    print("final balance omg: %f" % omg_balance)
    print("final balance eth: %f" % eth_balance)

    return


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--mode",
                        default='check',
                        help="model type: check; mine")
    args = parser.parse_args()

    fcoin = Fcoin()
    api_key = os.environ["FCOIN_API_KEY"]
    api_sec = os.environ["FCOIN_API_SECRET"]
    fcoin.auth(api_key, api_sec)

    MODE = args.mode
    if MODE == 'check':
        check(fcoin=fcoin)
    elif MODE == 'mine':
        #eth_trades = ['fteth', 'zileth', 'icxeth', 'zipeth', 'omgeth']
        mining(fcoin=fcoin)
    elif MODE == 'test':
        while True:
            ret = fcoin.get_market_depth('L20', 'omgeth')
            lowest_ask = ret['data']['asks'][0]
            highest_bid = ret['data']['bids'][0]
Exemplo n.º 28
0
class App():
    def __init__(self):
        self.fcoin = Fcoin()
        self.fcoin.auth(config.api_key, config.api_secret)
        self.log = Log("")
        self.symbol = 'ftusdt'
        self.order_id = None
        self.dic_balance = defaultdict(lambda: None)
        self.time_order = time.time()
        self.oldprice = self.digits(self.get_ticker(), 6)
        self.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.count_flag = 0
        self.fall_rise = 0

    def digits(self, num, digit):
        site = pow(10, digit)
        tmp = num * site
        tmp = math.floor(tmp) / site
        return tmp

    def get_ticker(self):
        ticker = self.fcoin.get_market_ticker(self.symbol)
        self.now_price = ticker['data']['ticker'][0]
        self.log.info("now price%s" % self.now_price)
        return self.now_price

    def get_blance(self):
        dic_blance = defaultdict(lambda: None)
        data = self.fcoin.get_balance()
        if data:
            for item in data['data']:
                dic_blance[item['currency']] = balance(
                    float(item['available']), float(item['frozen']),
                    float(item['balance']))
        return dic_blance

    def save_csv(self, array):
        with open("data/trade.csv", "a+", newline='') as w:
            writer = csv.writer(w)
            writer.writerow(array)

    def reset_save_attrubute(self):
        self.now_price = 0.0
        self.type = 0
        self.fee = 0.0
        self.order_id = None

    def my_process(self):
        self.dic_balance = self.get_blance()
        ft = self.dic_balance["ft"]
        usdt = self.dic_balance["usdt"]
        print("usdt ---", usdt.available, "ft----", ft.available)
        price = self.digits(self.get_ticker(), 6)
        new_old_price = abs(price / self.oldprice - 1) * 100
        print("new price --", price)
        print("old price --", self.oldprice)
        print("price波动百分比----", new_old_price)

        if 0.001 < new_old_price < 1:
            if price > self.oldprice and self.fall_rise < 6:
                self.fall_rise = self.fall_rise + 1
            elif price < self.oldprice and self.fall_rise > -6:
                self.fall_rise = self.fall_rise - 1
            print("跌涨标志----", self.fall_rise)

            order_list = self.fcoin.list_orders(symbol=self.symbol,
                                                states="submitted")["data"]
            print("size", len(order_list))
            if not order_list or len(order_list) < 3:
                self.count_flag = 0
                data = self.fcoin.get_market_depth("L20", self.symbol)
                bids_price = data["data"]["bids"][0]
                asks_price = data["data"]["asks"][0]
                dif_price = (asks_price * 0.001 + bids_price * 0.001) / 2
                if self.fall_rise > 3 or (price > self.oldprice
                                          and new_old_price > 0.4):
                    print("涨--------------")
                    bids_dif = bids_price - dif_price * 0.6
                    asks_dif = asks_price + dif_price * 1.5
                elif self.fall_rise < -3 or (price < self.oldprice
                                             and new_old_price > 0.4):
                    print("跌---------------")
                    bids_dif = bids_price - dif_price * 1.5
                    asks_dif = asks_price + dif_price * 0.6
                else:
                    print("平衡-------------")
                    bids_dif = bids_price - dif_price
                    asks_dif = asks_price + dif_price

                bids_price_b = self.digits(bids_dif, 6)
                print("bids_price", bids_price_b)
                asks_price_a = self.digits(asks_dif, 6)
                print("asks_price", asks_price_a)
                print("交易差------", (asks_price_a - bids_price_b) * 1000)

                asks_data = self.fcoin.sell(self.symbol, asks_price_a, 6)
                if asks_data:
                    print("sell success")
                bids_data = self.fcoin.buy(self.symbol, bids_price_b, 6)
                if bids_data:
                    print("buy success")
            else:
                self.count_flag = self.count_flag + 1
                time.sleep(2)
                print("sleep end")
                if len(order_list) >= 1:
                    self.log.info("cancel order {%s}" % order_list[-1])
                    print("****************cancel order ***********")
                    order_id = order_list[-1]['id']
                    self.count_flag = 0
                    data = self.fcoin.cancel_order(order_id)
                    self.log.info("cancel result {%s}" % data)
        else:
            print("##########当前波动无效###########")
        self.oldprice = price

    def process(self):
        price = self.digits(self.get_ticker(), 6)
        self.oldprice.append(price)
        self.dic_balance = self.get_blance()
        ft = self.dic_balance['ft']
        usdt = self.dic_balance['usdt']

        self.log.info("usdt has--[%s]   ft has--[%s]" %
                      (usdt.balance, ft.balance))

        order_list = self.fcoin.list_orders(symbol=self.symbol,
                                            states='submitted')['data']
        print(order_list)
        self.log.info("order trading: %s" % order_list)

        if not order_list or len(order_list) < 2:
            if usdt and abs(price / self.oldprice[len(self.oldprice) - 2] -
                            1) < 0.02:
                if price * 2 < self.oldprice[len(self.oldprice) -
                                             2] + self.oldprice[
                                                 len(self.oldprice) - 3]:
                    amount = self.digits(usdt.available / price * 0.25, 2)
                    if amount > 5:
                        data = self.fcoin.buy(self.symbol, price, amount)
                        if data:
                            self.fee = amount * 0.001
                            self.order_id = data['data']
                            self.time_order = time.time()
                            self.type = 1
                            self.log.info(
                                'buy success price--[%s] amout--[%s] fee--[%s]'
                                % (price, amount, self.fee))
                else:
                    if float(ft.available) * 0.25 > 5:
                        amount = self.digits(ft.available * 0.25, 2)
                        data = self.fcoin.sell(self.symbol, price, amount)
                        if data:
                            self.fee = amount * price * 0.001
                            self.time_order = time.time()
                            self.order_id = data['data']
                            self.type = 2
                            self.log.info(
                                "sell success price--[%s] amout--[%s] fee--[%s]"
                                % (price, amount, self.fee))

            else:
                print('价格波动过大 %s' % usdt)
                self.log.info("价格波动过大%s" % usdt)
        else:
            print('system busy')
            if len(order_list) >= 1:
                self.log.info("cancel order {%s}" % order_list[-1])
                order_id = order_list[-1]['id']
                data = self.fcoin.cancel_order(order_id)
                self.log.info("cancel result {%s}" % data)
                if data:
                    if order_list[len(order_list) -
                                  1]['side'] == 'buy' and order_list[
                                      len(order_list) -
                                      1]['symbol'] == 'ftusdt':
                        self.fee = -float(
                            order_list[len(order_list) - 1]['amount']) * 0.001
                    elif order_list[len(order_list) -
                                    1]['side'] == 'sell' and order_list[
                                        len(order_list) -
                                        1]['symbol'] == 'ftusdt':
                        self.fee = -float(
                            order_list[len(order_list) - 1]['amount']) * float(
                                order_list[len(order_list) -
                                           1]['price']) * 0.001
                    self.type = 3
                    self.order_id = order_id

    def loop(self):
        while True:
            try:
                self.my_process()
                # time1 = time.time()
                # self.process()
                # array = [self.order_id,self.now_price,self.type,self.fee,self.symbol,time.strftime('%Y-%m-%d %H:%M:%S')]
                # if self.type != 0:
                #     self.save_csv(array)
                # self.log.info("--------success-------")
                # time2 = time.time()
                # self.log.info("app time--%s"% str(time2-time1))
                time.sleep(5)
            except Exception as e:
                self.log.info(e)
                print(e)
Exemplo n.º 29
0
# -*- coding: utf-8 -*-
"""

@author: 躺着也挣钱
QQ群 :  422922984

"""

import pandas as pd
from fcoin3 import Fcoin
from datetime import datetime
#if python3 use
#from fcoin import Fcoin

fcoin = Fcoin()
fcoin.auth('key ', 'secret')

#取K线数据

ft_usdt = fcoin.get_candle('M3', 'ftusdt')  #M3 = 分钟线,   取150条数据

# 取得当前账户信息
print(fcoin.get_balance())

#
print(fcoin.get_symbols())

print(fcoin.get_currencies())

#
#print(fcoin.buy('fteth', 0.0001, 10))
Exemplo n.º 30
0
__author__ = 'Daemon1993'

import json
from fcoin3 import Fcoin
import threading
import time
from config import api_key
from config import api_secret

# 交易类型
symbol = 'btcusdt'
filled = 'filled'

# 初始化
fcoin = Fcoin()
# 授权
api_key = api_key
api_secret = api_secret
fcoin.auth(api_key, api_secret)

order_list = fcoin.list_orders(symbol=symbol, states=filled, limit=100)
print(json.dumps(order_list))
sum = 0
for order in order_list['data']:
    print(order['side'], order['price'], order['state'])
    sum += float(order['executed_value'])
print(sum)