Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class bcolors:
- HEADER = '\033[95m'
- OKBLUE = '\033[94m'
- OKCYAN = '\033[96m'
- OKGREEN = '\033[92m'
- WARNING = '\033[93m'
- FAIL = '\033[91m'
- ENDC = '\033[0m'
- BOLD = '\033[1m'
- UNDERLINE = '\033[4m'
- def initialize(state):
- state.number_offset_trades = 0;
- trailingEnabled = False
- trailingPerc = 10
- atrPeriod = 14
- stopLossEnabled = False
- takeProfitEnabled = False
- stopLossAtrMult = 2
- takeProfitAtrMult = 4
- SYMBOLS = ['BTCBUSD','ETHBUSD']
- @schedule(interval="12h", symbol=SYMBOLS)
- def handler(state, data):
- '''
- 1) Compute indicators from data
- '''
- PORTFOLIO_PERC_PER_BUY = 1/len(SYMBOLS)
- symbols = [{'data': data[symbol],'dataframe' : data[symbol].to_pandas()} for symbol in data.keys() if data[symbol]]
- for symbol in symbols:
- dataframe = symbol['dataframe']
- data = symbol['data']
- atr = data.atr(period=atrPeriod)
- # on erronous data return early (indicators are of NoneType)
- if atr is None:
- print("Missing some indicators data...")
- return
- current_price = data.close_last
- '''
- 2) Fetch portfolio
- > check liquidity (in quoted currency)
- > resolve buy value
- '''
- portfolio = query_portfolio()
- balance_quoted = portfolio.excess_liquidity_quoted
- quote_asset = portfolio.quoted
- portfolio_value = portfolio.portfolio_value
- balances = portfolio.balances
- position_open = portfolio.open_positions
- position_closed = portfolio.closed_positions
- # we invest only 80% of available liquidity
- #balance_quoted
- buy_value = float(portfolio_value) * PORTFOLIO_PERC_PER_BUY
- if buy_value > balance_quoted:
- buy_value = balance_quoted
- '''
- 3) Fetch position for symbol
- > has open position
- > check exposure (in base currency)
- '''
- position = query_open_position_by_symbol(data.symbol,include_dust=False)
- has_position = position is not None
- '''
- 4) Resolve buy or sell signals
- > create orders using the order api
- > print position information
- '''
- buySignal = True
- sellSignal = False
- #your strategy logic here. Should be sufficent setting changing buySignal and sellSignal in order to trigger orders
- if not has_position and buySignal:
- print("\n -------")
- print(bcolors.OKGREEN + "BUY" + bcolors.ENDC + f" - [{data.symbol}]: {buy_value:.2f} at { current_price:.4f}")
- print(f"portfolio: {portfolio_value:.3f}{quote_asset} - OPENPOS: {len(position_open)}")
- order = order_market_value(symbol=data.symbol, value=buy_value)
- if trailingEnabled:
- firstStopPrice = current_price-(current_price*trailingPerc)/100
- order_trailing_iftouched_amount(symbol=data.symbol, amount=-subtract_order_fees(order.quantity), trailing_percent= trailingPerc/100, stop_price=firstStopPrice)
- print(f"TS order created - {-order.quantity} at {firstStopPrice} ({trailingPerc}%)")
- elif stopLossEnabled or takeProfitEnabled:
- with OrderScope.one_cancels_others():
- if stopLossEnabled:
- stopLossPrice = current_price - (atr[-1]*stopLossAtrMult)
- stopLossOrder = order_iftouched_market_amount(data.symbol,amount=-subtract_order_fees(order.quantity),stop_price=stopLossPrice)
- stopLossPerc = ((current_price-stopLossPrice)/current_price)*100
- print(f"[{data.symbol}] - Stop loss order created at {stopLossPrice} ({stopLossPerc:.2f}%)")
- if takeProfitEnabled:
- takeProfitPrice = current_price + (atr[-1]*takeProfitAtrMult)
- takeProfitOrder = order_iftouched_market_amount(data.symbol,amount=-subtract_order_fees(order.quantity),stop_price=takeProfitPrice)
- takeProfitPerc = ((takeProfitPrice - current_price)/current_price)*100
- print(f"[{data.symbol}] - Take profit order created at {takeProfitPrice} ({takeProfitPerc:.2f}%)")
- elif has_position and sellSignal:
- print("\n -------")
- print(bcolors.FAIL + "SELL" + bcolors.ENDC + f" - [{data.symbol}]: {current_price:.4f}")
- print(f"portfolio: {portfolio_value:.3f}{quote_asset} - OPENPOS: {len(position_open)}")
- close_position(data.symbol)
- # 5) Check strategy profitability
- # > print information profitability on every offsetting trade
- if state.number_offset_trades < portfolio.number_of_offsetting_trades:
- pnl = query_portfolio_pnl()
- profitability = query_portfolio_profitablity()
- # print(f"Profitability: {profitability}")
- print(f"Accumulated Pnl of Strategy: {pnl}")
- offset_trades = portfolio.number_of_offsetting_trades
- number_winners = portfolio.number_of_winning_trades
- winrate = (number_winners/offset_trades) *100
- print(f"Win Rate: {winrate:.2f}% ({number_winners}/{offset_trades})" )
- print(f"Best trade Return : {portfolio.best_trade_return:.2%} - {profitability.bestTradePnl:.2f}")
- print(f"Worst trade Return : {portfolio.worst_trade_return:.2%} - {profitability.worstTradePnl:.2f}")
- print(f"Average Profit per Winning Trade : {portfolio.average_profit_per_winning_trade:.2f}")
- print(f"Average Loss per Losing Trade : {portfolio.average_loss_per_losing_trade:.2f}")
- # reset number offset trades
- state.number_offset_trades = portfolio.number_of_offsetting_trades
- print("------- \n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement