首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >安装python bot,使其适合于Binance的期货交易

安装python bot,使其适合于Binance的期货交易
EN

Stack Overflow用户
提问于 2022-03-11 00:14:18
回答 1查看 511关注 0票数 1

我是一个新手程序员,谁试图学习和肯定奋斗。我做了近10年的交易,现在正试图实现自动化。遇到慷慨的“兼职拉里”,并试图更新他的代码,使其适合未来。它可以完美地生成信号,但我对长(买入)/Short(出售)订单( def check_buy_sell_signals( df )部分)有问题。任何帮助都将不胜感激。“兼职拉里”的所有学分

代码语言:javascript
运行
复制
import ccxt
import config
import schedule
import pandas as pd
pd.set_option('display.max_rows', None)
from datetime import datetime
import time
import numpy as np
import warnings
warnings.filterwarnings('ignore')
#binancefutures
exchange = ccxt.binanceusdm({
    'apiKey': 'apiKey',
    'secret': 'secret',
})
lev = exchange.set_leverage(10, 'ETH/USDT')
def tr(data):
    data['previous_close']=data['close'].shift(1)
    data['high-low']=abs(data['high'] - data['low'])
    data['high-pc']=abs(data['high'] - data['previous_close'])
    data['low-pc']=abs(data['low']-data['previous_close'])
    tr=data[['high-low', 'high-pc', 'low-pc']].max(axis=1)
    return tr
def atr(data, period=10):#supertrend variables
    data['tr']=tr(data)
    print("calculate average true range")
    atr=data['tr'].rolling(period).mean()
    return atr
def supertrend(df, period=10, atr_multiplier=1.4):
    hl2=(df['high']+df['low'])/2
    print("calculating supertrend")
    df['atr']=atr(df, period=period)
    df['upperband']= hl2 + (atr_multiplier*df['atr'])
    df['lowerband']= hl2 -(atr_multiplier*df['atr'])
    df['in_uptrend']=True
    for current in range(1, len(df.index)):
        previous=current-1
        if df['close'][current] > df['upperband'][previous]:
            df['in_uptrend'][current]=True
        elif df['close'][current] < df['lowerband'][previous]:
            df['in_uptrend'][current]=False
        else:
            df['in_uptrend'][current] = df['in_uptrend'][previous]
            if df['in_uptrend'][current] and df['lowerband'][current] < df['lowerband'][previous]:
                df['lowerband'][current] = df['lowerband'][previous]
            if not df['in_uptrend'][current] and df['upperband'][current] > df['upperband'][previous]:
                df['upperband'][current] = df['upperband'][previous]
    return(df)
global in_position
def check_buy_sell_signals(df):
    in_position = False
    to_use = (exchange.fetch_balance().get('USDT').get('free'))
    price = ((exchange.fetchTicker('ETH/USDT').get('last')))-10
    bal = to_use / price
    print("Checking for buy or sell signals")
    print(df.tail(5))
    last_row_index = len(df.index)- 1
    previous_row_index = last_row_index - 1
    if not df['in_uptrend'][previous_row_index] and df['in_uptrend'][last_row_index]:
            print("changed to uptrend, buy")
            if not in_position:
                order = exchange.create_market_buy_order('ETH/USDT', bal)
                print(order)
                in_position = True
    if df['in_uptrend'][previous_row_index] and not df['in_uptrend'][last_row_index]:
            print("changed to downtrend, sell")
            if not in_position:
                order = exchange.create_market_sell_order('ETH/USDT', bal)
                print(order)
                in_position = True
    if df['in_uptrend'][previous_row_index] and not df['in_uptrend'][last_row_index]:
            print("trend changed")
            if in_position:
                close_position = binance.create_order(symbol=symbol, type="MARKET", side="sell", amount=pos['positionAmt'], params={"reduceOnly": True})
                print(order)
                in_position = False
    if not df['in_uptrend'][previous_row_index] and df['in_uptrend'][last_row_index]:
            print("trend changed")
            if in_position:
                order = exchange.create_market_buy_order('ETH/USDT', bal)
                close_position = binance.create_order(symbol=symbol, type="MARKET", side="buy", amount=pos['positionAmt'], params={"reduceOnly": True})
                print(order)
                in_position = False
def run_bot():
    print("Fetching new bars for", datetime.now())
    bars = exchange.fetch_ohlcv('ETH/USDT', timeframe='1h', limit=100)
    df = pd.DataFrame(bars[:-1], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
    df['timestamp']=pd.to_datetime(df['timestamp'], unit='ms')
    supertrend_data = supertrend(df)
    check_buy_sell_signals(supertrend_data)
schedule.every(1).minutes.do(run_bot)
while True:
    schedule.run_pending()
    time.sleep(1)
EN

回答 1

Stack Overflow用户

发布于 2022-03-11 10:44:04

此答案从as-is代码中删除基数错误,以避免其有缺陷的操作(由于这种隐藏错误而导致其有状态的原始丢失):

代码语言:javascript
运行
复制
import ccxt
import time
import config
import schedule
import numpy  as np
import pandas as pd; pd.set_option( 'display.max_rows', None )
import warnings;     warnings.filterwarnings( 'ignore' )

from   datetime import datetime
from   my_code  import tr, atr, supertrend, run_bot
from   fut_sig  import check_buy_sell_signals

#binancefutures
exchange = ccxt.binanceusdm( { 'apiKey': 'apiKey',
                               'secret': 'secret',
                                }
                             )
lev = exchange.set_leverage( 10, 'ETH/USDT' )
#----------------------------------#
global in_position                 # it does not save you here
#----------------------------------# on global scope

schedule.every( 1 ).minutes.do( run_bot )

while True:
    schedule.run_pending()
    time.sleep( 1 )

问题是,在函数范围内,如果不在此声明global,一个新的符号in_trade将与False的值相关联,而在该函数的范围内,其所有更改都将与该局部作用域符号相关,即有效地掩盖在全局范围上定义的“全局”变量。尊重全局符号的显式表示法--如这里的语句global in_position中所示--为Python解释器提供了一个明确的指示,使其不再尝试做任何其他事情,而是在遇到符号名“具有相同名称”时使用已经存在的已定义的global符号操作:

fut_sig.py

代码语言:javascript
运行
复制
def check_buy_sell_signals(df):
    #------------------------------# it would get masked here
    global in_position             # if not DECLARED to be a global
    #------------------------------# so avoiding a new, local one from masking it
    in_position = False
    to_use = (exchange.fetch_balance().get('USDT').get('free'))
    price = ((exchange.fetchTicker('ETH/USDT').get('last')))-10
    bal = to_use / price
    print("Checking for buy or sell signals")
    print(df.tail(5))
    last_row_index = len(df.index)- 1
    previous_row_index = last_row_index - 1
    if not df['in_uptrend'][previous_row_index] and df['in_uptrend'][last_row_index]:
            print("changed to uptrend, buy")
            if not in_position:
                order = exchange.create_market_buy_order('ETH/USDT', bal)
                print(order)
                in_position = True
    if df['in_uptrend'][previous_row_index] and not df['in_uptrend'][last_row_index]:
            print("changed to downtrend, sell")
            if not in_position:
                order = exchange.create_market_sell_order('ETH/USDT', bal)
                print(order)
                in_position = True
    if df['in_uptrend'][previous_row_index] and not df['in_uptrend'][last_row_index]:
            print("trend changed")
            if in_position:
                close_position = binance.create_order(symbol=symbol, type="MARKET", side="sell", amount=pos['positionAmt'], params={"reduceOnly": True})
                print(order)
                in_position = False
    if not df['in_uptrend'][previous_row_index] and df['in_uptrend'][last_row_index]:
            print("trend changed")
            if in_position:
                order = exchange.create_market_buy_order('ETH/USDT', bal)
                close_position = binance.create_order(symbol=symbol, type="MARKET", side="buy", amount=pos['positionAmt'], params={"reduceOnly": True})
                print(order)
                in_position = False

my_code.py

代码语言:javascript
运行
复制
def run_bot():
    print("Fetching new bars for", datetime.now())
    bars = exchange.fetch_ohlcv('ETH/USDT', timeframe='1h', limit=100)
    df = pd.DataFrame(bars[:-1], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
    df['timestamp']=pd.to_datetime(df['timestamp'], unit='ms')
    supertrend_data = supertrend(df)
    check_buy_sell_signals(supertrend_data)

def tr(data):
    data['previous_close']=data['close'].shift(1)
    data['high-low']=abs(data['high'] - data['low'])
    data['high-pc']=abs(data['high'] - data['previous_close'])
    data['low-pc']=abs(data['low']-data['previous_close'])
    tr=data[['high-low', 'high-pc', 'low-pc']].max(axis=1)
    return tr

def atr(data, period=10):#supertrend variables
    data['tr']=tr(data)
    print("calculate average true range")
    atr=data['tr'].rolling(period).mean()
    return atr

def supertrend(df, period=10, atr_multiplier=1.4):
    hl2=(df['high']+df['low'])/2
    print("calculating supertrend")
    df['atr']=atr(df, period=period)
    df['upperband']= hl2 + (atr_multiplier*df['atr'])
    df['lowerband']= hl2 -(atr_multiplier*df['atr'])
    df['in_uptrend']=True
    for current in range(1, len(df.index)):
        previous=current-1
        if df['close'][current] > df['upperband'][previous]:
            df['in_uptrend'][current]=True
        elif df['close'][current] < df['lowerband'][previous]:
            df['in_uptrend'][current]=False
        else:
            df['in_uptrend'][current] = df['in_uptrend'][previous]
            if df['in_uptrend'][current] and df['lowerband'][current] < df['lowerband'][previous]:
                df['lowerband'][current] = df['lowerband'][previous]
            if not df['in_uptrend'][current] and df['upperband'][current] > df['upperband'][previous]:
                df['upperband'][current] = df['upperband'][previous]
    return(df)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71432266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档