def dataset(self): self.exchange = ccxt.ftx({ 'apiKey': '', 'secret': '', 'enableRateLimit': True }) timeframe = self.timeframe limit = self.limit ohlcv = self.exchange.fetch_ohlcv(self.pair_data, timeframe, limit=limit) ohlcv = self.exchange.convert_ohlcv_to_trading_view(ohlcv) df = pd.DataFrame(ohlcv) df.t = df.t.apply(lambda x: datetime.fromtimestamp(x)) df = df[df.t > self.start_test] df = df.set_index(df['t']) df = df.drop(['t'], axis=1) df = df.rename(columns={ "o": "open", "h": "high", "l": "low", "c": "close", "v": "volume" }) dataset = df dataset = dataset.dropna() return dataset
def __init__(self): self.env = BinanceEnvironment( api_url='https://dex-asiapacific.binance.org', wss_url='wss://dex.binance.org/api/', hrp='bnb') with open('bnb_real_key.txt', 'r') as f: key = f.readline() # for testing # self.env = BinanceEnvironment.get_testnet_env() # with open('bnb_key.txt', 'r') as f: # key = f.readline() f.close() self.client = HttpApiClient(env=self.env) self.wallet = Wallet(key, env=self.env) self.address = self.wallet.address self.ftx = ccxt.ftx({ 'apiKey': '6p37l5AXOzIgFzfeSzkcuPhuaYcw3GcpJrU83ROy', 'secret': '3SphoJJ6Gl_w5pPPkGmQpKbVGN9oPiUgxqs4ob_H' }) #self.assets = ['USD', 'USDT'] self.assets = ['USD'] self.BNB_BUSD = 'BNB.BUSD-BD1' self.pool = THORChain()
def _create_ftx(self): ftx = ccxt.ftx({ 'enableRateLimit': False, }) wrap_object(ftx, rate_limiter_group=self.ftx_rate_limiter, wrap_defs=ftx_wrap_defs()) return ftx
def create_exchange(exchange_id): exchange = None if exchange_id == 'ftx': exchange = ccxt.ftx({ 'enableRateLimit': True, 'rateLimit': 2000, 'timeout': 30000, }) return exchange
def dataset (self , pair_data = "BTC-USD"): self.exchange = ccxt.ftx({'apiKey': '' ,'secret': '' , 'enableRateLimit': True }) # timeframe = self.timeframe # limit = self.limit # ohlcv = self.exchange.fetch_ohlcv(pair_data,timeframe , limit=limit ) # ohlcv = self.exchange.convert_ohlcv_to_trading_view(ohlcv) # df = pd.DataFrame(ohlcv) # df.t = df.t.apply(lambda x : datetime.fromtimestamp(x)) # df = df.set_index(df['t']) ; df = df.drop(['t'] , axis= 1 ) # df = df.rename(columns={"o": "open", "h": "high" , "l": "low", "c": "close" , "v": "volume"}) # close = df['close'][-1] return self.exchange.fetch_ticker(pair_data)['info']['bid']
def _loop(self, raise_error=False): intervals = [15, 60, 300, 900, 3600, 14400, 86400] price_types = [ None, ] ftx = ccxt.ftx() markets = list( map(lambda x: x['name'], ftx.publicGetMarkets()['result'])) current_futures = list( map(lambda x: x['name'], ftx.publicGetFutures()['result'])) expired_futures = list( map(lambda x: x['name'], ftx.publicGetExpiredFutures()['result'])) unique_symbols = list(set(markets + current_futures + expired_futures)) for symbol in unique_symbols: for interval in intervals: if self.min_interval is not None and interval < self.min_interval: continue for price_type in price_types: try: self.store.get_df_ohlcv(exchange='ftx', market=symbol, interval=interval, price_type=price_type, force_fetch=True) except KeyboardInterrupt: raise except Exception as e: if raise_error: raise self.logger.error('exception ' + traceback.format_exc()) time.sleep(60) try: if symbol in (current_futures + expired_futures): self.store.get_df_fr(exchange='ftx', market=symbol, force_fetch=True) except KeyboardInterrupt: raise except Exception as e: if raise_error: raise self.logger.error('exception ' + traceback.format_exc()) time.sleep(60)
def dataset(self): self.exchange = ccxt.ftx({ 'apiKey': '', 'secret': '', 'enableRateLimit': True }) ohlcv = self.exchange.fetch_ohlcv(self.pair_data, self.timeframe, limit=500) ohlcv = self.exchange.convert_ohlcv_to_trading_view(ohlcv) df = pd.DataFrame(ohlcv) df.t = df.t.apply(lambda x: datetime.fromtimestamp(x)) return df
def webhook(): """Combine all functions in actions.py, and run flask server""" if request.method == 'POST': print('*' * 60) # Parse the string data from tradingview into a python dict data = parse_webhook(request.get_data(as_text=True))[0] tail = parse_webhook(request.get_data(as_text=True))[1] message = tail if (data['type'] != "Skip") and (get_token() == data['key']): # Check that the key is correct print(' [Alert Received] ') print(tail) for account, account_info in config.Accounts.items(): if account_info['Name'] in data['BotName']: exchange = ccxt.ftx({ 'apiKey': account_info['exchangeapi'], 'secret': account_info['exchangesecret'], 'enableRateLimit': True, }) if account_info['Subaccount'] == 'Yes': exchange.headers = { 'FTX-SUBACCOUNT': account_info['SubName'], } send_order(data, tail, exchange, account_info['Name'], account_info['Track']) if account_info['UseTelegram'] == 'Yes': send_to_telegram(tail, data) if account_info['UseTwitter'] == 'Yes': post_tweet(message) else: pass return '', 200 if data['type'] == "Skip": print(' [ALERT ONLY - NO TRADE] ') print(tail) for account, account_info in config.Accounts.items(): if account_info['Name'] in data['BotName']: if account_info['UseTelegram'] == 'Yes': send_to_telegram(tail, data) if account_info['UseTwitter'] == 'Yes': post_tweet(message) print('*' * 60, '/n') return '', 200 else: abort(400)
def __init__(self, api_key, api_secret, subaccount, what_symbol): self.what_symbol = what_symbol self.api_key = api_key self.api_secret = api_secret self.subaccount = subaccount self.exchange = ccxt.ftx({ 'apiKey': self.api_key, 'secret': self.api_secret, 'enableRateLimit': True, }) if self.subaccount == "": print("This is Main Account") else: self.exchange.headers = { 'FTX-SUBACCOUNT': self.subaccount, }
def ex_api(self): if self.ex == "ftx": exchange = ccxt.ftx({ 'apiKey': self.apiKey, 'secret': self.secret, 'enableRateLimit': True }) elif self.ex == "deribit": exchange = ccxt.deribit({ 'apiKey': self.apiKey, 'secret': self.secret, 'enableRateLimit': True, "urls": { "api": "https://test.deribit.com" } }) return exchange
import sys import ccxt import os from pprint import pprint import time # replace with your key / secret key = os.environ.get('ftx_key') secret = os.environ.get('ftx_secret') exchange = ccxt.ftx({ 'apiKey': key, 'secret': secret }) exchange.load_markets() # cancel all open orders for symbol def cancel_all(symbol): res = exchange.cancel_all_orders(symbol) pprint(res) # create and execute a scaled order def scaled_order(symbol, side, total, start_price, end_price, num_orders): # cast command line args to proper types for math total = float(total) start_price = float(start_price) end_price = float(end_price) num_orders = int(num_orders)
import os import sys root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt # noqa: E402 # make sure your version is 1.51+ print('CCXT Version:', ccxt.__version__) exchange = ccxt.ftx({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', # "headers": { # "FTX-SUBACCOUNT": "YOUR_SUBACCOUNT" # } }) markets = exchange.load_markets() # exchange.verbose = True # uncomment for debugging all_results = {} symbol = None since = None limit = 200 end_time = exchange.milliseconds() while True:
import ccxt import json import pandas as pd import tkinter # api and secret apiKey = "API KEY" secret = "SECRET KEY" subaccount = "GLADIATOR(B)" password = "******" # exchange detail exchange = ccxt.ftx({ 'apiKey': apiKey, 'secret': secret, 'password': password, 'enableRateLimit': True, }) # Sub Account Check if subaccount == "0": print("This is Main Account") else: exchange.headers = { 'ftx-SUBACCOUNT': subaccount, } def getProduct(): print("PRODUCT =", exchange.symbols)
threshold = 10 testing = True import ccxt import pytz from datetime import datetime, timedelta utc = pytz.utc from time import sleep import os ftx = ccxt.ftx({ 'enableRateLimit': True, 'apiKey': os.environ['ftxkey'], 'secret': os.environ['ftxsecret'], }) print(dir(ftx)) bulls = [] bears = [] lts = [] winners = {} winners['bull'] = {} winners['bear'] = {} losers = {} precisions = {} losers['bull'] = {} losers['bear'] = {} wd = -1 dttarget = None wdchanges = 0 mids = {}
import pandas as pd import json import csv from csv import DictWriter import time import ccxt import gspread from datetime import datetime # กำหนด PARAMETER ที่จำเป็น apiKey = "XXXXXXXXXXXXXXXXXX" #SENSEBOT1 secret = "XXXXXXXXXXXXXXXXXX" #SENSEBOT1 exchange = ccxt.ftx({ 'apiKey': apiKey, 'secret': secret, 'enableRateLimit': True }) exchange.headers = { 'FTX-SUBACCOUNT': "XXXXXXXXXXXXXXXXXX", } #SENSEBOT1 pair = "BTC-PERP" portName = "CF CALCULATION BOT" def updatepaired(): dfpaired = pd.read_csv("pairedOrder.csv") dfpositionBuy = pd.read_csv("holdBuy.csv") dfpositionSell = pd.read_csv("holdSell.csv")
from pprint import pprint import ccxt pprint(ccxt.exchanges) ftx_test = ccxt.ftx() ''' 可以联通的交易所有 bitflyer,bittrex,ftx,kraken,xena, ''' Stock = "TRX/USDT" pprint(ftx_test.fetch_ticker(Stock)) print(ftx_test.urls)
# -*- coding: utf-8 -*- import os import sys from pprint import pprint root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt # noqa: E402 print('CCXT Version:', ccxt.__version__) exchange = ccxt.ftx({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', }) exchange.load_markets() # exchange.verbose = True # uncomment for debugging purposes if necessary symbol = 'BTC/USD:USD' # change for your symbol positions = exchange.fetch_positions() positions_by_symbol = exchange.index_by(positions, 'symbol') if symbol in positions_by_symbol: position = positions_by_symbol[symbol] type = 'market' side = 'sell' if position['side'] == 'long' else 'buy' amount = position['contracts'] price = None
msg = f'Account : {acc}' msg1 = f'Symbol : {pair}' msg2 = f'Error : {traceback.format_exc()}' sendline = requests.post( url, headers=headers, data={'message': '\n' + msg + '\n' + msg1 + '\n' + msg2}) # ============================================================================== # Connect Server ftx = ccxt.ftx({ 'apiKey': apikey, 'secret': secret_key, 'enableRateLimit': True }) if acc == "0": acc = "Main Account" else: ftx.headers = { 'FTX-SUBACCOUNT': acc, } # ============================================================================== # Connect GGS scope = [ "https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive.file",
# -*- coding: utf-8 -*- import os import sys root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt # noqa: E402 # make sure your version is 1.51+ print('CCXT Version:', ccxt.__version__) exchange = ccxt.ftx() markets = exchange.load_markets() # exchange.verbose = True # uncomment for debugging all_trades = {} symbol = 'BTC/USD' since = None limit = 200 end_time = exchange.milliseconds() start_time = end_time - 1 * 60 * 60 * 1000 # 1 hour of history for example while end_time > start_time: print('------------------------------------------------------------------') params = { 'end_time': int(end_time / 1000),
def loginx(): return (ccxt.ftx({ 'FTX-SUBACCOUNT': 'BuySide', 'apiKey': '197k2kYpGvyHMy__2H0WGVoHU_TPNkuydWtiig0h', 'secret': 'toncOlJhZfKO48jb6WLUJ59G67Z6-2EP2uVWCeWh', }))
import os import sys from pprint import pprint root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt # noqa: E402 print('CCXT Version:', ccxt.__version__) exchange = ccxt.ftx({ 'enableRateLimit': True, 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', }) exchange.load_markets() # exchange.verbose = True # uncomment for debugging purposes if necessary symbol = 'BTC/USD:USD' # change for your symbol positions = exchange.fetch_positions() positions_by_symbol = exchange.index_by(positions, 'symbol') if symbol in positions_by_symbol: position = positions_by_symbol[symbol] type = 'market' side = 'sell' if position['side'] == 'long' else 'buy' amount = position['contracts']
def loginx(): return (ccxt.ftx({ 'FTX-SUBACCOUNT': 'SellSide', 'apiKey': '5EsdFqBumKhLnX6BLAXcWSWj54EuquB0QpCIu6ZE', 'secret': 'iCWYk3XiJetOAz3WehDdaPXbPxdTj5w2kk9zZ7pK', }))
help='set lowest lending hour rate', default=1e-5) # ~ 8.76 % / year if __name__ == '__main__': args = parser.parse_args() config = { 'apiKey': API_KEY, 'secret': APY_SECRET, } subaccount = args.account if subaccount is not None: config['headers'] = {'FTX-SUBACCOUNT': subaccount} client = ccxt.ftx(config) # get balance balances = client.fetch_balance() coin = args.coin for item in balances['info']['result']: if item['coin'] == coin: balance = item['total'] break else: print(balances) raise Exception(f'result not found for {coin}') # renew lending body = {"coin": coin, "size": balance, "rate": args.rate} res = client.private_post_spot_margin_offers(body)
import tkinter import matplotlib.pyplot as plt from IPython.display import display from datetime import datetime import time plt.style.use('seaborn-white') plt.rcParams["figure.figsize"] = [15, 6] apiKey = "--------------------------------" #@param ["--------------------------------"] {allow-input: true} secret = "-----------------------------" #@param ["-----------------------------"] {allow-input: true} subaccount = "---main = 0 , sub acc----" #@param ["---main = 0 , sub acc----"] {allow-input: true} exchange = ccxt.ftx({ 'apiKey': apiKey, 'secret': secret, 'subaccount': subaccount, 'enbleRateLimit': True }) if subaccount == "0": print("This is Main Account") else: exchange.headers = { 'FTX-SUBACCOUNT': subaccount, } #@title ฟังก์ชั่น คำนวนการใช้งาน def getBalance(): print("PORT BALANCE =", exchange.fetch_balance())
# Currency of subaccount balance EQUITY_CURRENCY = 'USD' # Key for exchange API API_KEY = '' # Secret for exchange API API_SECRET = '' # Name of exchange subaccount SUBACCOUNT_NAME = '' # Prohibits immediate repositioning if stop loss is exceeded WAIT_IF_STOP_LOSS = True # Access FTX cryptocurrency exchange exchange = ccxt.ftx({ 'apiKey': API_KEY, 'secret': API_SECRET, 'headers': { 'FTX-SUBACCOUNT': SUBACCOUNT_NAME, }, }) # Verify login was successful exchange.check_required_credentials() def retrieve_trading_data() -> pd.DataFrame: longest_lookback = 4 * max([MA_LOOKBACK, EMA_LOOKBACK, ATR_LOOKBACK + 1]) # First day of lookback start_point = int(time.time() - longest_lookback * 86400) * 1000 trading_data = exchange.fetch_ohlcv(symbol=CRYPTO_SYMBOL, timeframe=DATA_TIMEFRAME, since=start_point) df = pd.DataFrame(trading_data)
messenger = Sendline(token) ############################ Setting ############################################# API_Key = 'put your api key' API_secret = 'put your api secret' Subaccount = 'put your subaccount name' Pair = "SRM/USD" Token_name = "SRM" Rebalance_value = 1000 ## put your rebalance value ## ############################### เรียกใช้งาน API ############################################# FTX = ccxt.ftx({ 'apiKey' : API_Key , 'secret' : API_secret , 'headers': {'FTX-SUBACCOUNT': 'put your subaccount name'}, 'enableRateLimit': True }) print(messenger.sendtext('Exchange = ' + str(FTX))) ## Network checking / Line notify ## ################################# Price of SRM ############################################# SRM_value = json.dumps(FTX.fetch_ticker('SRM/USD')) ## pair 'SRM/USD'/ u can change to pair what u want ## Price_SRM = json.loads(SRM_value) print(messenger.sendtext('SRM = ' + str(Price_SRM['last']))) ## Line notify ## ############################### Balance ####################################### while True: balance = FTX.fetch_balance()
import ccxt from concurrent.futures import ThreadPoolExecutor, as_completed import json from decimal import getcontext, Decimal from sendMail import sendMail from balance_monitor import getBalance from diskcache import Index import time getcontext().prec = 6 ftx = ccxt.ftx() def _public_get_futures_future_name_stats(name): result = ftx.public_get_futures_future_name_stats(name) result = result["result"] result["name"] = name["future_name"] return result def get_future_stats(names): with ThreadPoolExecutor() as executor: return executor.map(_public_get_futures_future_name_stats, names) def get_perpetual(futures): """获取永续资金率""" perpetuals = [i for i in futures if i["perpetual"]] perpetual_names = [{"future_name": i["name"]} for i in perpetuals] nextFundingRate_data = get_future_stats(perpetual_names)
API_KEY = config['Settings']['API_KEY'] API_SECRET = config['Settings']['API_SECRET'] SUB_ACCOUNT = config['Settings']['SUB_ACCOUNT'] COIN = config['Settings']['COIN'] COIN_TARGET_PC = float(config['Settings']['COIN_TARGET_PC']) THRESHOLD_PC = float(config['Settings']['THRESHOLD_PC']) RB_TIME_SECS = int(config['Settings']['RB_TIME_SECS']) UPPER_LIMIT = (COIN_TARGET_PC + THRESHOLD_PC) / 100 LOWER_LIMIT = (COIN_TARGET_PC - THRESHOLD_PC) / 100 STATEMENT_FILE_PATH = os.path.join(BOT_DIR, 'statement.csv') # Set limit variables LOGGER = BotLogger(SUB_ACCOUNT, LINE_TOKEN) FTX = ccxt.ftx({ "apiKey": API_KEY, "secret": API_SECRET, "enableRateLimit": True }) FTX.headers = {"FTX-SUBACCOUNT": SUB_ACCOUNT} if len(SUB_ACCOUNT) > 0 else {} # TODO optimize """ bot create order by "ask" price so if we fast/lucky enough then it will be fine but if the order did not completed then the order will stay forever which makes the bot stuck """
sheetname = 'Data2' # เรียกข้อมูลใน google sheet และตั้งให้ คอลัม Product เป็น index ไว้ให้ pandas เรียกใช้ df = get_as_dataframe( gc.open(sheetname).worksheet('Monitor')).set_index('Product') dfMap = get_as_dataframe(gc.open(sheetname).worksheet('Map')) dfTradeLog = get_as_dataframe(gc.open(sheetname).worksheet('TradeLog')) #### รายละเอียด ก่อนเทรด ------------------------------------------------------- Balance = 'USD' whatsymbol = "XRP-PERP" ########### ตั้งค่า API ------------------------------------------------------- subaccount = 'Benz-Test-Bot' # ถ้ามี ซับแอคเคอร์ของ FTX exchange = ccxt.ftx({ 'apiKey': '*************', 'secret': '**************', 'enableRateLimit': True, }) if subaccount == "": print("This is Main Account") else: exchange.headers = { 'FTX-SUBACCOUNT': subaccount, } ########### ---------------------------------------------------------------------------- def updatee(): # ----- ตั้งค่า Map ว่าแต่ล่ะโซนควรมีกระสุนหรือไม่----- Set_MapTrigger()
def init_supported_exchanges(): objects = { "acx": ccxt.acx(), "aofex": ccxt.aofex(), "bequant": ccxt.bequant(), "bibox": ccxt.bibox(), "bigone": ccxt.bigone(), "binance": ccxt.binance(), "bitbank": ccxt.bitbank(), "bitbay": ccxt.bitbay(), "bitfinex": ccxt.bitfinex(), "bitflyer": ccxt.bitflyer(), "bitforex": ccxt.bitforex(), "bithumb": ccxt.bithumb(), "bitkk": ccxt.bitkk(), "bitmax": ccxt.bitmax(), "bitstamp": ccxt.bitstamp(), "bittrex": ccxt.bittrex(), "bitz": ccxt.bitz(), "bl3p": ccxt.bl3p(), "bleutrade": ccxt.bleutrade(), "braziliex": ccxt.braziliex(), "btcalpha": ccxt.btcalpha(), "btcbox": ccxt.btcbox(), "btcmarkets": ccxt.btcmarkets(), "btctradeua": ccxt.btctradeua(), "bw": ccxt.bw(), "bybit": ccxt.bybit(), "bytetrade": ccxt.bytetrade(), "cex": ccxt.cex(), "chilebit": ccxt.chilebit(), "coinbase": ccxt.coinbase(), "coinbasepro": ccxt.coinbasepro(), "coincheck": ccxt.coincheck(), "coinegg": ccxt.coinegg(), "coinex": ccxt.coinex(), "coinfalcon": ccxt.coinfalcon(), "coinfloor": ccxt.coinfloor(), "coinmate": ccxt.coinmate(), "coinone": ccxt.coinone(), "crex24": ccxt.crex24(), "currencycom": ccxt.currencycom(), "digifinex": ccxt.digifinex(), "dsx": ccxt.dsx(), "eterbase": ccxt.eterbase(), "exmo": ccxt.exmo(), "exx": ccxt.exx(), "foxbit": ccxt.foxbit(), "ftx": ccxt.ftx(), "gateio": ccxt.gateio(), "gemini": ccxt.gemini(), "hbtc": ccxt.hbtc(), "hitbtc": ccxt.hitbtc(), "hollaex": ccxt.hollaex(), "huobipro": ccxt.huobipro(), "ice3x": ccxt.ice3x(), "independentreserve": ccxt.independentreserve(), "indodax": ccxt.indodax(), "itbit": ccxt.itbit(), "kraken": ccxt.kraken(), "kucoin": ccxt.kucoin(), "lakebtc": ccxt.lakebtc(), "latoken": ccxt.latoken(), "lbank": ccxt.lbank(), "liquid": ccxt.liquid(), "livecoin": ccxt.livecoin(), "luno": ccxt.luno(), "lykke": ccxt.lykke(), "mercado": ccxt.mercado(), "oceanex": ccxt.oceanex(), "okcoin": ccxt.okcoin(), "okex": ccxt.okex(), "paymium": ccxt.paymium(), "poloniex": ccxt.poloniex(), "probit": ccxt.probit(), "southxchange": ccxt.southxchange(), "stex": ccxt.stex(), "surbitcoin": ccxt.surbitcoin(), "therock": ccxt.therock(), "tidebit": ccxt.tidebit(), "tidex": ccxt.tidex(), "upbit": ccxt.upbit(), "vbtc": ccxt.vbtc(), "wavesexchange": ccxt.wavesexchange(), "whitebit": ccxt.whitebit(), "yobit": ccxt.yobit(), "zaif": ccxt.zaif(), "zb": ccxt.zb() } return objects