Ejemplo n.º 1
0
def do_load():
    db = MySQLdb.connect("127.0.0.1", "root", "123456", "qos", charset='utf8')
    cursor = db.cursor()

    sql = "select a.key, a.secret from app_certification a, app_account b where a.id = b.certification_id order by b.updated_at limit 1"
    cursor.execute(sql)
    key, secret = cursor.fetchone()
    api = fcoin.authorize(key, secret)
    data = api.get_balance()["data"]

    insert_template = "insert into app_balance (id, currency, category, available, frozen, balance, created_at, updated_at) values ('%s', '%s', '%s', %s, %s,  %s, %s, %s)"
    update_template = "update app_balance set available=%s, frozen=%s, balance=%s, updated_at=%s where currency='%s' and category='%s'"

    for i in data:
        try:
            sql = insert_template % (str(uuid.uuid4()).replace(
                "-",
                ""), i['currency'], i['category'], i['available'], i['frozen'],
                                     i['balance'], 'now()', 'now()')
            cursor.execute(sql)
        except MySQLdb.IntegrityError:
            sql = update_template % (i['available'], i['frozen'], i['balance'],
                                     'now()', i['currency'], i['category'])
            cursor.execute(sql)
        # print(sql)

    db.commit()
    db.close()
Ejemplo n.º 2
0
    def run(self):
        api = fcoin.authorize(FCoinConfig.public_key, FCoinConfig.secret_key)
        try:
            ticker_data = api.get_ticker(self.base +
                                         self.quote)['data']['ticker']
        except Exception:
            ticker_data = api.get_ticker(self.base +
                                         self.quote)['data']['ticker']

        self.trading_dag.remove_edge(self.base, self.quote)
        self.trading_dag.add_weighted_edges_from([(self.base, self.quote,
                                                   ticker_data[2])])
        self.trading_dag[self.base][self.quote]['size'] = ticker_data[3]

        self.trading_dag.remove_edge(self.quote, self.base)
        self.trading_dag.add_weighted_edges_from([(self.quote, self.base,
                                                   1 / ticker_data[4])])
        self.trading_dag[self.quote][self.base]['size'] = ticker_data[5]
Ejemplo n.º 3
0
    def __init__(self):

        api = fcoin.authorize(config.key, config.secret)
        self.fcoin_api = api
        currencies = self.fcoin_api.symbols()
        self.symbles = {}
        print "支持的usdt交易币种信息如下:"
        for i in currencies.itertuples():
            if i.quote_currency == "usdt":
                self.symbles[i.name] = [i.amount_decimal, i.price_decimal]
        for i, j in self.symbles.items():
            print "币种:%s,价格精度:%s 数量精度:%s" % (i, j[0], j[1])
        if config.symbol["name"] not in self.symbles:
            raise Exception("币种配置错误!!")
        _ = self.symbles[config.symbol["name"]]
        if config.symbol["price_decimal"] > _[1]:
            raise Exception("price_decimal配置错误,允许的范围是1-%s" % _[1])
        if config.symbol["amount_decimal"] > _[0]:
            raise Exception("amount_decimal配置错误,允许的范围是1-%s" % _[0])

        "fix 官方库下单的的bug"

        DataAPI._old_signed_request = DataAPI.signed_request

        def signed_request(self, method, url, **params):
            while 1:
                if url == "orders":
                    url = HTORD % SERVER
                try:
                    result = DataAPI._old_signed_request(
                        self, method, url, **params)
                    assert result != None
                except Exception as e:
                    print "调用api%s发生错误!%s,正在重试" % (url, str(e))
                    time.sleep(0.5)
                else:
                    return result

        DataAPI.signed_request = signed_request

        self.buy_order_id = None
        self.filled_buy_order_list = []
        self.order_list = {}
        self._init_log()
Ejemplo n.º 4
0
import fcoin
import time

api = fcoin.authorize('cc6110ca00234e768cc4436c69e582c2', '78d616712b5b461c99f677dc9629de48')
server_time = api.server_time()
print(server_time)
# now_ms = int(time.time())
# api.market.ping(now_ms)



# fcoin_ws = fcoin.init_ws()
# topics = ["depth.L20.ethbtc", "depth.L100.btcusdt"]
# fcoin_ws.handle(print)
# fcoin_ws.sub(topics)
Ejemplo n.º 5
0
import  fcoin
import threading
import configparser
import time

cf = configparser.ConfigParser()
cf.read("fcoin.ini")
key = cf.get("Key", "Public")
secret = cf.get("Key", "Secret")
api = fcoin.authorize(key, secret)
BalanceThread=None
BalanceLock = threading.RLock()
BalanceActions=set()
OrderThread=None
OrderLock = threading.RLock()
OrderActions=set()
OrderList={}

class BalanceThreadClass(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        global api,BalanceThread,BalanceLock,BalanceActions
        print("Balance线程启动")
        try:
            while True:
                Result = api.get_balance()
                with BalanceLock:
                    Actions=BalanceActions.copy()
                if Result != None and "data" in Result:
                    for cur in Actions:
Ejemplo n.º 6
0
import fcoin
from chengutil import mysqlutil, util

api = fcoin.authorize('key', 'secret')
print(api.server_time())

symbol = api.symbols()
symbol = symbol['data']
print('symbols len >>>', len(symbol))

db = mysqlutil.init()
cursor = db.cursor()

try:

    for s in symbol:
        sql = '''
            SELECT COUNT(_id) FROM `xcm_fcoin_symbol` WHERE symbol=%s'''
        cursor.execute(sql, (s['name']))
        rows = cursor.fetchall()
        if rows[0][0] > 0:
            continue

        print('symbol >>>', s['name'])
        sql = '''
            INSERT INTO `xcm_fcoin_symbol` 
            (symbol, base, quote, price_decimal, amount_decimal) 
            VALUES (%s, %s, %s, %s, %s)'''
        param = (s['name'], s['base_currency'], s['quote_currency'],
                 s['price_decimal'], s['amount_decimal'])
        print(param)
Ejemplo n.º 7
0
# -*- coding:utf-8 -*-
# fcoin的api调用工具类
import fcoin
import traceback
import time
from fcoin.cons import *
import json

# api类
api_key = '6ee8c12a0b004c1c839f7d38645c1873'
api_secret = '711a4cc685ee4a02a3958072edb1a1f7'
api = fcoin.authorize(api_key, api_secret)

# 配置信息
# python使用ft币总量的比例,全部是100
python_use = 5
# 设置ft不备卖出的比例,全部是100
lock_ft = 15
symbol = 'ftusdt'


class fcoin_api_utils(object):
    def candles(self, resolution, symbol):
        while True:
            try:
                return api.public_request(GET, api.http_market + 'candles/%s/%s' % (resolution, symbol))
            except Exception:
                traceback.print_exc()

    # 分析波动趋势
    def fluctuation_trend(self):
Ejemplo n.º 8
0
exchange_names_input = 'fcoin'

key_fcoin = sys.argv[1]
secret_fcoin = sys.argv[2]
exchange_names = exchange_names_input.split(',')

print('Using exchanges:{}'.format(exchange_names))

symbols_watch = ['BTC', 'USDT']

remove_pairs = []

loop = asyncio.get_event_loop()

api_auth = fcoin.authorize(key_fcoin, secret_fcoin)


async def create_order(symbol, side, price, amount):
    symbol_transformed = f"{symbol.replace('/', '').lower()}"

    if all_pairs_decimal[symbol] == 0:
        amount_str = str(int(amount))
    else:
        amount_str = str(amount)

    if side == 'buy':
        amount_str = str(round(amount * price, 1))

    order_create_param = fcoin.order_create_param(symbol_transformed, side,
                                                  'market', amount_str)
Ejemplo n.º 9
0
# coding=utf-8
import fcoin
from conf import config

api = fcoin.authorize(config.key, config.secret)
print api.accounts_balance

from fcoin.WebsocketClient import WebsocketClient

bids = []
asks = []


class HandleWebsocket(WebsocketClient):
    def handle(self, msg):
        print "#############################"
        for key, value in msg.items():
            print key, value
            if key == "bids":
                global bids
                bids = value
            if key == "asks":
                global asks
                asks = value


import time
from threading import Thread

ws = HandleWebsocket()
topics = {
Ejemplo n.º 10
0
 def __init__(self):
     self.trading_dag = {}
     self.api = fcoin.authorize(FCoinConfig.public_key,
                                FCoinConfig.secret_key)
     self.trading_pairs_list = []
Ejemplo n.º 11
0
def sell_ft(api, price):
    try:
        res = api.sell("fteth", price, 5)
        if res["status"] == 0:
            return True
        else:
            return False
    except:
        print "sell_ft failed"


if __name__ == '__main__':
    if len(sys.argv) != 4:
        print "python fcoin.py api.key api.secret number"
        sys.exit(-1)
    api = fcoin.authorize(sys.argv[1],sys.argv[2])
    #api = DataAPI(sys.argv[1],sys.argv[2])
    ft_price = get_ft_price(api)

    for i in range(1, int(sys.argv[3])):
        print "count :", i
        ft_price = get_ft_price(api)
        eth_balance = get_eth_balance(api)

        print "----start buy ft coins----"
        print "eth of balance : ", eth_balance
        print "ft price : ", ft_price
        if float(ft_price) * 5 < eth_balance:
            print "buy 5 ft coins."
            buy_ft(api, ft_price)
        else:
Ejemplo n.º 12
0
 def initWithKeySecret(self, key, secret):
     self.api = fcoin.authorize(key, secret)