Advertisement
akanoce

Trality_Order_Issue

Mar 2nd, 2022
1,043
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.37 KB | None | 0 0
  1. import pandas as pd
  2. import numpy as np
  3.  
  4. class bcolors:
  5.     HEADER = '\033[95m'
  6.     OKBLUE = '\033[94m'
  7.     OKCYAN = '\033[96m'
  8.     OKGREEN = '\033[92m'
  9.     WARNING = '\033[93m'
  10.     FAIL = '\033[91m'
  11.     ENDC = '\033[0m'
  12.     BOLD = '\033[1m'
  13.     UNDERLINE = '\033[4m'
  14.  
  15.  
  16. def get_supertrend(data, atr_period, atr_multiplier):
  17.    
  18.     # ATR
  19.     atr = data.atr(period=atr_period)
  20.     atr_df = atr.to_pandas()
  21.    
  22.     data_df = data.to_pandas()
  23.  
  24.     high, low, close = data_df['high'],data_df['low'],data_df['close']
  25.      # HL2 is simply the average of high and low prices
  26.     hl2 = (high + low) / 2
  27.     # upperband and lowerband calculation
  28.     # notice that final bands are set to be equal to the respective bands
  29.     final_upperband = upperband = hl2 + (atr_multiplier * atr_df['atr'])
  30.     final_lowerband = lowerband = hl2 - (atr_multiplier * atr_df['atr'])
  31.  
  32.     # print(final_upperband)
  33.    
  34.    
  35.     # initialize Supertrend column to True
  36.     supertrend = [1] * len(data_df)
  37.     for i in range(1, len(data_df.index)):
  38.         curr, prev = i, i-1
  39.        
  40.         # if current close price crosses above upperband
  41.         if close[curr] > final_upperband[prev]:
  42.             supertrend[curr] = 1
  43.         # if current close price crosses below lowerband
  44.         elif close[curr] < final_lowerband[prev]:
  45.             supertrend[curr] = -1
  46.         # else, the trend continues
  47.         else:
  48.             supertrend[curr] = supertrend[prev]
  49.            
  50.             # adjustment to the final bands
  51.             if supertrend[curr] == 1 and final_lowerband[curr] < final_lowerband[prev]:
  52.                 final_lowerband[curr] = final_lowerband[prev]
  53.             if supertrend[curr] == -1 and final_upperband[curr] > final_upperband[prev]:
  54.                 final_upperband[curr] = final_upperband[prev]
  55.  
  56.         # to remove bands according to the trend direction
  57.         if supertrend[curr] == 1:
  58.             final_upperband[curr] = np.nan
  59.         else:
  60.             final_lowerband[curr] = np.nan
  61.  
  62.     # print(supertrend)
  63.     final_df = pd.DataFrame({
  64.         'Supertrend': supertrend,
  65.         'Final Lowerband': final_lowerband,
  66.         'Final Upperband': final_upperband
  67.     }, index=data_df.index)
  68.     # print(final_df.tail(1))
  69.  
  70.     active_band = final_lowerband[-1] if not np.isnan(final_lowerband[-1]) else final_upperband[-1]
  71.     with PlotScope.root(data.symbol):
  72.         plot_line(f"supertrend ({atr_period}/{atr_multiplier})", active_band)
  73.     return supertrend, active_band
  74.     # return pd.DataFrame({
  75.     #     'Supertrend': supertrend,
  76.     #     'Final Lowerband': final_lowerband,
  77.     #     'Final Upperband': final_upperband
  78.     # }, index=df.index)
  79.    
  80.  
  81. def initialize(state):
  82.     state.number_offset_trades = 0;
  83.  
  84.  
  85.  
  86. stPeriod = 10
  87. stMult = 3
  88.  
  89. maFilterEnabled = False
  90. maFilterPeriod = 200
  91. maFilterType = 'EMA'
  92.  
  93. sellSignalsEnabled = False
  94.  
  95. trailingEnabled = True  
  96. trailingPerc = 20
  97.  
  98. atrPeriod = 14
  99. stopLossEnabled = False
  100. takeProfitEnabled = False
  101. stopLossAtrMult = 2
  102. takeProfitAtrMult = 4
  103.  
  104.  
  105. SYMBOLS = ["ETHBUSD","SOLBUSD"]
  106.  
  107. @schedule(interval="1d", symbol=SYMBOLS)
  108. def HANDLER1(state, data):
  109.     handler(state,data)
  110.  
  111.  
  112. def handler(state, data):
  113.     '''
  114.    1) Compute indicators from data
  115.    '''
  116.     PORTFOLIO_PERC_PER_BUY = 1/len(SYMBOLS)
  117.     # print(f"Symbols length: {len(SYMBOLS)}")
  118.     symbols = [{'data': data[symbol],'dataframe' : data[symbol].to_pandas()} for symbol in data.keys() if data[symbol]]
  119.  
  120.     for symbol in symbols:
  121.         dataframe = symbol['dataframe']
  122.         data = symbol['data']
  123.  
  124.         # update super trend indicator
  125.         st, st_band = get_supertrend( data, stPeriod, stMult)
  126.  
  127.         atr = data.atr(period=atrPeriod)
  128.        
  129.  
  130.         if maFilterEnabled:
  131.             if maFilterType == 'EMA':
  132.                 trendMa = data.ema(period=maFilterPeriod)
  133.             elif maFilterType in ['SMA','MA']:
  134.                 trendMa = data.ma(period=maFilterPeriod)
  135.             elif maFilterType in ['HMA']:
  136.                 trendMa = data.hma(period=maFilterPeriod)
  137.  
  138.         # on erronous data return early (indicators are of NoneType)
  139.         if (maFilterEnabled and not trendMa):
  140.             return
  141.  
  142.         current_price = data.close_last
  143.        
  144.         '''
  145.        2) Fetch portfolio
  146.            > check liquidity (in quoted currency)
  147.            > resolve buy value
  148.        '''
  149.        
  150.         portfolio = query_portfolio()
  151.         balance_quoted = portfolio.excess_liquidity_quoted
  152.         quote_asset = portfolio.quoted
  153.         portfolio_value = portfolio.portfolio_value
  154.         balances = portfolio.balances
  155.         position_open = portfolio.open_positions
  156.         position_closed = portfolio.closed_positions
  157.         # we invest only 80% of available liquidity
  158.         #balance_quoted
  159.         buy_value = float(portfolio_value) * PORTFOLIO_PERC_PER_BUY
  160.         if buy_value > balance_quoted:
  161.             buy_value = balance_quoted
  162.        
  163.        
  164.         '''
  165.        3) Fetch position for symbol
  166.            > has open position
  167.            > check exposure (in base currency)
  168.        '''
  169.  
  170.         position = query_open_position_by_symbol(data.symbol,include_dust=False)
  171.         has_position = position is not None
  172.  
  173.         '''
  174.        4) Resolve buy or sell signals
  175.            > create orders using the order api
  176.            > print position information
  177.            
  178.        '''
  179.         bullishTrendFilter = not maFilterEnabled or current_price > trendMa[-1]
  180.         bearishTrendFilter = not maFilterEnabled or current_price < trendMa[-1]
  181.        
  182.         sellSignal = False
  183.         buySignal = False
  184.         if st[-1] > 0:
  185.             buySignal = True
  186.         else:
  187.             sellSignal = True
  188.  
  189.         if has_position:
  190.             if sellSignal and sellSignalsEnabled:
  191.                 print("\n -------")
  192.                 print(bcolors.FAIL + "SELL" + bcolors.ENDC + f" - [{data.symbol}]: {current_price:.4f}")
  193.                 print(f"portfolio: {portfolio_value:.3f}{quote_asset} - OPENPOS: {len(position_open)}")
  194.                 close_position(data.symbol)
  195.         else:
  196.             # print(f"Level: {level} dir:{direction} ")
  197.             if buySignal and bullishTrendFilter:
  198.                 print("\n -------")
  199.                 print(bcolors.OKGREEN + "BUY" + bcolors.ENDC + f" - [{data.symbol}]: {buy_value:.2f} at { current_price:.4f}")
  200.                 print(f"portfolio: {portfolio_value:.3f}{quote_asset} - OPENPOS: {len(position_open)}")
  201.                 order = order_market_value(symbol=data.symbol, value=buy_value)
  202.                 if trailingEnabled:
  203.                     firstStopPrice = current_price-(current_price*trailingPerc)/100
  204.                     order_trailing_iftouched_amount(symbol=data.symbol, amount=-subtract_order_fees(order.quantity), trailing_percent= trailingPerc/100, stop_price=firstStopPrice)
  205.                     print(f"TS order created - {-order.quantity}  at {firstStopPrice} ({trailingPerc}%)")
  206.                 elif stopLossEnabled or takeProfitEnabled:
  207.                     with OrderScope.one_cancels_others():
  208.                         if stopLossEnabled:
  209.                             stopLossPrice = current_price - (atr[-1]*stopLossAtrMult)
  210.                             stopLossOrder = order_iftouched_market_amount(data.symbol,amount=-subtract_order_fees(order.quantity),stop_price=stopLossPrice)
  211.                             stopLossPerc = ((current_price-stopLossPrice)/current_price)*100
  212.                             print(f"[{data.symbol}] - Stop loss order created at {stopLossPrice} ({stopLossPerc:.2f}%)")
  213.                         if takeProfitEnabled:
  214.                             takeProfitPrice = current_price + (atr[-1]*takeProfitAtrMult)
  215.                             takeProfitOrder = order_iftouched_market_amount(data.symbol,amount=-subtract_order_fees(order.quantity),stop_price=takeProfitPrice)
  216.                             takeProfitPerc = ((takeProfitPrice - current_price)/current_price)*100
  217.                             print(f"[{data.symbol}] - Take profit order created at {takeProfitPrice} ({takeProfitPerc:.2f}%)")
  218.         ''' 5) Check strategy profitability
  219.            > print information profitability on every offsetting trade
  220.        '''
  221.        
  222.         if state.number_offset_trades < portfolio.number_of_offsetting_trades:
  223.            
  224.             pnl = query_portfolio_pnl()
  225.             profitability = query_portfolio_profitablity()
  226.            
  227.             # print(f"Profitability: {profitability}")
  228.             print(f"Accumulated Pnl of Strategy: {pnl}")
  229.            
  230.             offset_trades = portfolio.number_of_offsetting_trades
  231.             number_winners = portfolio.number_of_winning_trades
  232.             winrate = (number_winners/offset_trades) *100
  233.  
  234.             print(f"Win Rate: {winrate:.2f}% ({number_winners}/{offset_trades})" )
  235.             print(f"Best trade Return : {portfolio.best_trade_return:.2%} - {profitability.bestTradePnl:.2f}")
  236.             print(f"Worst trade Return : {portfolio.worst_trade_return:.2%} - {profitability.worstTradePnl:.2f}")
  237.             print(f"Average Profit per Winning Trade : {portfolio.average_profit_per_winning_trade:.2f}")
  238.             print(f"Average Loss per Losing Trade : {portfolio.average_loss_per_losing_trade:.2f}")
  239.             # reset number offset trades
  240.             state.number_offset_trades = portfolio.number_of_offsetting_trades
  241.             print("------- \n")
  242.  
  243.  
  244.  
  245.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement