def sell(cls, _start, high): """ Monta e executa uma negociação de venda. recebe o preço mais alto do momento para calcular a limitação de perca da negociação. """ high = float('{:.4f}'.format(high+(high*0.02))) order_sell = { "order": { "units": cls._units_sell, "instrument": cls._instrument, "timeInForce": 'FOK', "type": "MARKET", "positionFill": "DEFAULT", "stopLossOnFill": { "price": str(high).decode('utf8') } } } print ("STOP LOSS: ", high) if _start == 1: r = orders.OrderCreate(cls.account_id, data=order_sell) print cls.client.request(r) _start=_start+1 else: r = orders.OrderCreate(cls.account_id, data=order_sell) print cls.client.request(r) time.sleep(1) r = orders.OrderCreate(cls.account_id, data=order_sell) print cls.client.request(r) return _start, 'SELL'
def buy(cls, _start, low): """ Monta e executa uma negociação de compra. recebe o preço mais baixo do momento para calcular a limitação de perca da negociação. """ low = float('{:.4f}'.format(low-(low*0.02))) order_buy = { "order": { "units": cls._units_buy, "instrument": cls._instrument, "timeInForce": 'FOK', "type": "MARKET", "positionFill": "DEFAULT", "stopLossOnFill": { "price": str(low).decode('utf8') } } } print ("STOP LOSS: ", low) if _start == 1: r = orders.OrderCreate(cls.account_id, data=order_buy) print cls.client.request(r) _start=_start+1 else: r = orders.OrderCreate(cls.account_id, data=order_buy) print cls.client.request(r) time.sleep(1) r = orders.OrderCreate(cls.account_id, data=order_buy) print cls.client.request(r) return _start, 'BUY'
def main(self): self.resistance = max(self.data[(uniVar.count - 6):uniVar.count]) self.support = max(self.data[(uniVar.count - 6):uniVar.count]) #oanda parameters mktOrderLong = MarketOrderRequest( instrument=uniVar.pair, units=self.lots(), takeProfitOnFill=TakeProfitDetails(price=self.resistance).data, stopLossOnFill=StopLossDetails(price=self.support).data) mktOrderShort = MarketOrderRequest( instrument=uniVar.pair, units=(self.lots() * -1), takeProfitOnFill=TakeProfitDetails(price=self.support).data, stopLossOnFill=StopLossDetails(price=self.resistance).data) #Trading conditions if self.getTrades() == 0: print("Looking for trades.") if self.enterLong() == True: api = oandapyV20.API(access_token=uniVar.key) r = orders.OrderCreate(uniVar.accountID, data=mktOrderLong.data) api.request(r) self.status == 'Currently Trading' self.currentTrade == 'Long' print('Trade Executed') elif self.enterShort() == True: api = oandapyV20.API(access_token=uniVar.key) r = orders.OrderCreate(uniVar.accountID, data=mktOrderShort.data) api.request(r) self.status == 'Currently Trading' self.currentTrade == 'Long' print('Trade Executed') elif self.enterLong() and self.enterShort() == False: print('No open trades, currently looking for one') else: if self.currentTrade == 'Short': if self.enterLong() == True: self.closePosition() self.status == 'Not Trading' print('Short Trade exited') else: print('No Short exits, currently looking for one') elif self.currentTrade == 'Long': if self.enterShort() == True: self.closePosition() self.status == 'Not Trading' print('Long Trade exited') else: print('No Long exits, currently looking for one') else: self.kill = True print('Kill switch initiated, closing down')
def main(self): self.resistance = max(self.data[(userVals.count - 6):userVals.count]) self.support = min(self.data[(userVals.count - 6):userVals.count]) # Oanda Parameters mktOrderLong = MarketOrderRequest( instrument=userVals.pair, units=self.lots(), takeProfitOnFill=TakeProfitDetails(price=self.resistance).data, stopLossOnFill=StopLossDetails(price=self.support).data) mktOrderShort = MarketOrderRequest( instrument=userVals.pair, units=(self.lots() * -1), takeProfitOnFill=TakeProfitDetails(price=self.support).data, stopLossOnFill=StopLossDetails(price=self.resistance).data) # Trading Conditions if self.getTrades() == 0: print "Looking for trades." if self.enterLong() == True: api = oandapyV20.API(access_token=userVals.key) r = orders.OrderCreate(userVals.accountID, data=mktOrderLong.data) api.request(r) self.status == "Trading" self.currentTrade == "Long" print "Trade Executed" elif self.enterShort() == True: api = oandapyV20.API(access_token=userVals.key) r = orders.OrderCreate(userVals.accountID, data=mktOrderShort.data) api.request(r) self.status == "Trading" self.currentTrade == "Short" print "Trade Executed" elif self.enterLong() and self.enterShort() == False: print "No Trades Open, Looking for Entry..." else: if self.currentTrade == "Short": if self.enterLong() == True: self.closePosition() self.status == "Not Trading" print "Trade Exited" else: print "No exits.. Looking" elif self.currentTrade == "Long": if self.enterShort() == True: self.closePosition() self.status == "Not Trading" print "Trade Exited" else: print "No exits.. Looking" else: self.kill = True print "Error, Closing down."
def place_order_single_pair_21(self, forex_pair, num_of_candles, interval, take_profit, stop_loss): import json import oandapyV20.endpoints.orders as orders from oandapyV20.contrib.requests import MarketOrderRequest from oandapyV20.contrib.requests import StopLossOrderRequest from oandapyV20.contrib.requests import TakeProfitOrderRequest self.indicators(forex_pair, num_of_candles, interval) if "JPY" in forex_pair: take_profit_pair = take_profit * 0.01 stop_loss_pair = stop_loss * 0.01 price_gap = 5 * 0.01 elif "HKD" in forex_pair: take_profit_pair = take_profit * 0.001 stop_loss_pair = stop_loss * 0.001 price_gap = 5 * 0.001 else: take_profit_pair = take_profit * 0.0001 stop_loss_pair = stop_loss * 0.0001 price_gap = 5 * 0.0001 if self.ema_20_60[-1] >= self.close_prices_60[-1] <= self.ema_60[-1] and \ self.close_prices_60[-1] - self.open_prices_60[-6] <= price_gap: mo = MarketOrderRequest(instrument=forex_pair, units=self.pairs_units_140[forex_pair]) r = orders.OrderCreate(self.accountID, data=mo.data) # ? perform the request rv = self.client.request(r) print(json.dumps(rv, indent=4)) trade_id = rv["orderFillTransaction"]["tradeOpened"]["tradeID"] open_trade_price = float(rv["orderFillTransaction"]["price"]) if "JPY" in forex_pair: stop_loss_price = str(round(open_trade_price - stop_loss_pair, 3)) # - AS IT'S BEAR SCENARIO take_profit_price = str(round(open_trade_price - take_profit_pair, 3)) else: stop_loss_price = str(round(open_trade_price - stop_loss_pair, 5)) take_profit_price = str(round(open_trade_price - take_profit_pair, 5)) # - AS IT'S BEAR SCENARIO ordr_sl = StopLossOrderRequest(tradeID=trade_id, price=stop_loss_price) r_sl = orders.OrderCreate(self.accountID, data=ordr_sl.data) # perform the request rv_sl = self.client.request(r_sl) print(json.dumps(rv_sl, indent=4)) ordr_tp = TakeProfitOrderRequest(tradeID=trade_id, price=take_profit_price) r_tp = orders.OrderCreate(self.accountID, data=ordr_tp.data) # perform the request rv_tp = self.client.request(r_tp) print(json.dumps(rv_tp, indent=4))
def order(self, instrument, weight, price): # calculate TP/SL, these are fixed @ .5%/.25%; change to fit your needs p = str(price) p = p.split('.') p = len(p[1]) self.TP_long = round((price * 1.005), p) self.SL_long = round((price * 0.9975), p) self.TP_short = round((price * 0.995), p) self.SL_short = round( (price * 1.0025), p) # sometimes have an issue rounding with JPY crosses if self.weight > 0: mktOrder = MarketOrderRequest( instrument=instrument, units=weight, TakeProfitOnFill=TakeProfitDetails(price=self.TP_long).data, stopLossOnFill=StopLossDetails(price=self.SL_long).data) r = orders.OrderCreate(accountID, data=mktOrder.data) try: rv = self.api.request(r) if self.should_print == True: print(r.status_code) except V20Error as e: print(r.status_code, e) else: if self.should_print == True: print(json.dumps(rv, indent=4)) else: mktOrder = MarketOrderRequest( instrument=instrument, units=weight, TakeProfitOnFill=TakeProfitDetails(price=self.TP_short).data, stopLossOnFill=StopLossDetails(price=self.SL_short).data) r = orders.OrderCreate(accountId, data=mktOrder.data) try: rv = self.api.request(r) if self.should_print == True: print(r.status_code) except V20Error as e: print(r.status_code, e) else: if self.should_print == True: print(json.dumps(rv, indent=4)) return r.response
def create_order( self, order_price, stop_loss_price, take_profit_price, instrument="USD_JPY"): data = { "order": { "price": str(order_price), "units": "100", "stopLossOnFill": { "timeInForce": "GTC", "price": str(stop_loss_price) }, "takeProfitOnFill": { "timeInForce": "GTC", "price": str(take_profit_price) }, "instrument": instrument, "timeInForce": "GTC", "type": "LIMIT", "positionFill": "DEFAULT" } } r = orders.OrderCreate(accountID=self.account_id, data=data) # TODO: Orderテーブルに記録する return self.api.request(r)
def create_order(instrument, quantity, target, stop, direction): env = yaml.safe_load(open('/forex/programs/channel/configs/env.yaml', 'r')) if direction == 1: accountid = env['accountid_long'] else: accountid = env['accountid_short'] client = oandapyV20.API(access_token=env['client']) data = { 'order': { "units": quantity, "instrument": instrument, "timeInForce": "FOK", "type": "MARKET", "positionFill": "DEFAULT", 'takeProfitOnFill': { 'price': str(round(target, 5)), 'timeInForce': 'GTC' }, 'stopLossOnFill': { 'price': str(round(stop, 5)), 'timeInForce': 'GTC' } } } print(data) r = orders.OrderCreate(accountid, data=data) client.request(r) return int(r.response['orderCreateTransaction']['id'])
def order(self, quote, precision_digits, bet_size, currency, profit, stop): tp = {"timeInForce": "GTC", "price": str(round(abs(profit), precision_digits))} sl = {"timeInForce": "GTC", "price": str(round(abs(stop), precision_digits))} order = {"order": {"units": bet_size, "instrument": currency, "timeInForce": "FOK", "type": "LIMIT", "positionFill": "DEFAULT", "price": str(round(quote, precision_digits)), 'takeProfitOnFill': tp, 'stopLossOnFill': sl}} # client api = API(access_token=self.token) # create and process order requests r = orders.OrderCreate(accountID=self.account_id, data=order) print("processing : {}".format(r)) print("===============================") print(r.data) print('end of data r.data') try: response = api.request(r) except V20Error as e: print("V20Error: {}".format(e)) return False, 0.0, 0 else: print("Response: {}\n{}".format(r.status_code, json.dumps(response, indent=2))) try: return True, response['orderFillTransaction']['price'], response['orderFillTransaction']['id'] except: # TODO Improve warning and errors syntax and exception treatment Warning('Order failed to execute. Likely not to have a descent available price.') return False, 0.0, 0
def limit_order(instrument, price, units, tp_price=None, sl_price=None): data = { "order": { "price": "{0:.5f}".format(price), "timeInForce": "GTC", "instrument": instrument, "units": units, "type": "LIMIT", "positionFill": "DEFAULT" } } if tp_price is not None: data["order"]["takeProfitOnFill"] = { "price": "{0:.5f}".format(tp_price) } if sl_price is not None: data["order"]["stopLossOnFill"] = { "price": "{0:.5f}".format(sl_price), "timeInForce": "GTC" } r = orders.OrderCreate(accountID=account_id, data=data) client.request(r) return r.response
def create_order(pair, direction, oanda_api=oanda_api, oanda_account=oanda_account): # Calculate trade parameters q = 10000 if direction == 'sell': q = -q # Fix Trade Data data = { 'order': { "units": q, "instrument": pair, "timeInForce": "FOK", "type": "MARKET", "positionFill": "DEFAULT" } } # Place Order client = oandapyV20.API(access_token=oanda_api) r = orders.OrderCreate(oanda_account, data=data) try: client.request(r) return r.response except Exception as e: print(e) return r.response
def market_if_touched_order(instrument, price, units, tp_price=None, sl_price=None, my_id=None): if my_id is None: my_id = "0" data = { "order": { "price": "{0:.5f}".format(price), "timeInForce": "GTC", "instrument": instrument, "units": units, "type": "MARKET_IF_TOUCHED", "positionFill": "REDUCE_ONLY", "clientExtensions": { "comment": "Test", "tag": "strategy", "id": my_id } } } if tp_price is not None: data["order"]["takeProfitOnFill"] = {"price": "{0:.5f}".format(tp_price)} if sl_price is not None: data["order"]["stopLossOnFill"] = {"price": "{0:.5f}".format(sl_price), "timeInForce": "GTC"} r = orders.OrderCreate(accountID=account_id, data=data) client.request(r) return r.response
def send_order(self, order: Order) -> Trade: if order.side == constants.BUY: side = 1 elif order.side == constants.SELL: side = -1 order_data = { 'order': { 'type': order.order_type, 'instrument': order.product_code, 'units': order.units * side } } req = orders.OrderCreate(accountID=self.account_id, data=order_data) try: resp = self.client.request(req) logger.info(f'action=send_order resp={resp}') except V20Error as e: logger.error(f'action=send_order error={e}') raise order_id = resp['orderCreateTransaction']['id'] order = self.wait_order_complete(order_id) if not order: logger.error('action=send_order error=timeout') raise OrderTimeoutError return self.trade_details(order.filling_transaction_id)
def OrderCreate_pending(self, ticker, size, price, takeprofit=None, stoploss=None, trailingstop=None, requesttype='MarketIfTouchedOrder'): d = dict(instrument=ticker, units=size, price=price) if takeprofit: d['takeProfitOnFill'] = TakeProfitDetails(price=takeprofit).data if stoploss: d['stopLossOnFill'] = StopLossDetails(price=stoploss).data if trailingstop: d['trailingStopLossOnFill'] = TrailingStopLossDetails( distance=trailingstop).data if requesttype is 'MarketIfTouchedOrder': Order = MITOrderRequest(**d).data elif requesttype is 'LimitOrder': Order = LimitOrderRequest(**d).data elif requesttype is 'StopOrder': Order = StopOrderRequest(**d).data r = orders.OrderCreate(accountID=self.accountID, data=Order) return self.client.request(r)
def order_buy_calc(pair): d = { "XAG_USD": 41, "XAU_USD": 1, "CORN_USD": 300, "BCO_USD": 28, "NATGAS_USD": 493, "SUGAR_USD": 9150, "WHEAT_USD": 204, "XCU_USD": 360, "XPT_USD": 1, "SOYBN_USD": 109 } u = d.get(pair) order_buy = MarketOrderRequest(instrument=pair, units=u) r = orders.OrderCreate(accountID, data=order_buy.data) print("Processing long order on : {}".format(r)) print("====================") print(r.data) try: response = api.request(r) except V20Error as e: print("V20Error:{}".format(e)) else: print("Respose: {}\n{}".format(r.status_code, json.dumps(response, indent=2)))
def buy_if_touch(account_id, account_token, instrument, unit, buy_price, stl_price, tf_price, debug=False): if debug: account_id, client = use_our_token() else: client = account_token data = { "order": { "price": buy_price, "takeProfitOnFill": { "timeInForce": "GTC", "price": tf_price }, "stopLossOnFill": { "timeInForce": "GTC", "price": stl_price }, "timeInForce": "GTC", "instrument": instrument, "units": f"{unit}", "type": "MARKET_IF_TOUCHED", "positionFill": "DEFAULT", "clientExtensions": { "id": "77777", "tag": "66666", "comment": "NUEVE_AUTO_BOT" } } } try: r = orders.OrderCreate(account_id, data=data) client.request(r) print(r.response) return True, r.response['orderFillTransaction']['tradeOpened'][ 'tradeID'] except V20Error as ex: error_msg = ex.msg.split('"errorMessage":')[1].split(',')[0].replace( '}', '') # print(ex.msg.split('"errorMessage":')[1].split(',')[1].split('}')[0]) print(f"Error : {error_msg}") return False, error_msg except Exception as ex: template = "Exception type {0}. Arguments:{1!r}" message = template.format(type(ex).__name__, ex.args) print(f"Error : {message}") return False, message
def make_order(kind: str, units: int, order_type: str): if kind not in ["buy", "sell"]: raise Exception('kind must be "buy" or "sell"') if order_type not in ["MARKET", "STOP", "LIMIT"]: raise Exception('order_type must be "MARKET", "STOP" or "LIMIT"\ \n"MARKET"...成行\ \n"STOP"...逆指値\ \n"LIMIT"...指値') if kind == 'buy': units = "+" + str(units) if kind == 'sell': units = "-" + str(units) order_data = { "order": { "instrument": "USD_JPY", "units": units, "type": order_type, } } try: o = orders.OrderCreate(accountID, data=order_data) api.request(o) return o.response except Exception: traceback.print_exc()
def make_mkt_order(self, amount, side): order = None if side == 'buy': order = { "order": { "instrument": self.ccy, "units": str(amount), "type": "MARKET", "positionFill": "DEFAULT" } } elif side == 'sell': order = { "order": { "instrument": self.ccy, "units": str(-amount), "type": "MARKET", "positionFill": "DEFAULT" } } try: req = orders.OrderCreate(self.account_id, data=order) resp_order = self.client.request(req) return float(resp_order['orderFillTransaction']['price']) except Exception as err: print("order not executed " + str(err)) return -1
def send_order(self, order: Order) -> Trade: if order.side == constants.BUY: units = order.units elif order.side == constants.SELL: units = -order.units order_data = { 'order': { 'type': order.order_type, 'instrument': order.product_code, 'units': units } } req = orders.OrderCreate(accountID=self.account_id, data=order_data) try: resp = self.client.request(req) logger.info(f'action=send_order resp={resp}') except V20Error as e: logger.error(f'action=send_order error={e}') raise order_id = resp['orderCreateTransaction']['id'] order = self.wait_order_complete(order_id) if not order: logger.error('action=send_order error=timeout') requests.post( settings.WEB_HOOK_URL, data=json.dumps({ 'text': f"send_order error=timeout", # 通知内容 })) raise OrderTimeoutError return self.trade_details(order.filling_transactionid)
def go_short(): # TODO: refactor this params = {"instruments": u.pair} r = pricing.PricingInfo(accountID=u.accountID, params=params) client.request(r) price_list = r.response.get('prices', {}) price_dict = price_list[0] bids = price_dict.get('bids') current_bids = bids[0] current_bid_price = float(current_bids.get('price')) take_profit = (current_bid_price-0.0050) # equivalent to 50 pips # TODO: Adjust the above and below position = position_size() try: order_data = MarketOrderRequest(instrument=u.pair, units=-position, # tp.Units(position).value takeProfitOnFill={ "price": tp.PriceValue(take_profit).value }, trailingStopLossOnFill={ "distance": "0.00500" }) r = orders.OrderCreate(u.accountID, data=order_data.data) client.request(r) sleep(5) trade() except Exception: print("Placing short order failed, check the logs.") logging.exception('Placing short order failed.')
def market_order_sl_distance(instrument, units, sl, tp): """ units can be positive or negative, stop loss (in pips) added/subtracted to price """ account_ID = account_id data = { "order": { "price": "", "stopLossOnFill": { "trailingStopLossOnFill": "GTC", "distance": str(sl) }, "takeProfitOnFill": { # "takeProfitOnFill": "GTC", "price": str(tp) }, # "distance": str(tp)}, "timeInForce": "FOK", "instrument": str(instrument), "units": str(units), "type": "MARKET", "positionFill": "DEFAULT" } } r = orders.OrderCreate(accountID=account_ID, data=data) client.request(r)
def order_buy_calc(pair, atr): price = (df_h[pair].iloc[:, 4]).astype(float)[0] sl = price - (1 * (atr * 0.50)) tp = price + (1 * (atr * 0.50)) # print("the price for", i, "is: ", price) # print("the tp for", i, "is: ", tp) # print("the sl for", i, "is: ", sl) takeProfitOnFillOrder = TakeProfitDetails(price=tp) StopLossOnFillOrder = StopLossDetails(price=sl) print(takeProfitOnFillOrder.data) print(StopLossOnFillOrder.data) # requests.post(url, data=order_b) order_buy = MarketOrderRequest(instrument=pair, units=1, takeProfitOnFill=takeProfitOnFillOrder.data, stopLossOnFill=StopLossOnFillOrder.data) r = orders.OrderCreate(accountID, data=order_buy.data) print("Processing : {}".format(r)) print("====================") print(r.data) try: response = api.request(r) except V20Error as e: print("V20Error:{}".format(e)) else: print("Respose: {}\n{}".format(r.status_code, json.dumps(response, indent=2)))
def open_order(self, instrument, units): # check if position is already open if units < 0: if self.order_book[instrument]['order_type'] is (not None and -1): print('Short: {} (holding)'.format(instrument)) return 1 elif units > 0: if self.order_book[instrument]['order_type'] is (not None and 1): print('Long: {} (holding)'.format(instrument)) return 1 else: print('Units specified: 0') return 1 # define parameters, create and send a request mkt_order = MarketOrderRequest(instrument=instrument, units=units) r = orders.OrderCreate(self.accountID, data=mkt_order.data) request_data = self.send_request(r) # check if request was fulfilled and save its ID if request_data is not 1: instrument = request_data['orderCreateTransaction']['instrument'] self.order_book[instrument]['tradeID'] = request_data[ 'lastTransactionID'] self.order_book[instrument]['order_type'] = -1 if units < 0 else 1 print('{}: {}'.format('Long' if units > 0 else 'Short', instrument)) return 0 else: return 1
def send_order(self, instrument, limit_price, units, stopLoss, takeProfit, gtdTime): orderbody = { "order": { "price": str(limit_price), "stopLossOnFill": { "timeInForce": "GTC", "price": str(stopLoss) }, "takeProfitOnFill": { "timeInForce": "GTC", "price": str(takeProfit) }, "timeInForce": "GTD", "gtdTime": str(gtdTime), "instrument": instrument, "units": str(units), "type": "LIMIT", "positionFill": "DEFAULT" } } r = orders.OrderCreate(accountID, data=orderbody) self.request(r) #self.client.request(r) print r.response
def make_a_deal(suggestion, trade_amount, ask_price, bid_price): amount_of_units = trade_amount if suggestion == "Go Long": direction = '' take_profit_price = float(ask_price) + 0.0001 else: direction = '-' take_profit_price = float(bid_price) - 0.0001 units_quantity = direction + str(amount_of_units) data = { "order": { "timeInForce": "FOK", "instrument": INSTRUMENTS, "units": units_quantity, "type": "MARKET", "positionFill": "DEFAULT", "takeProfitOnFill": { "timeInForce": "GTC", "price": str(take_profit_price) } } } client = oandapyV20.API(access_token=ACCESS_TOKEN) r = orders.OrderCreate(accountID=ACCOUNT_ID, data=data) client.request(r) print(r.response)
def order_sell_calc(pair, atr): price = (df_h[pair].iloc[:, 4]).astype(float)[0] sl = price - (1 * (atr * 0.50)) tp = price + (1 * (atr * 0.50)) takeProfitOnFillOrder = TakeProfitDetails(price=tp) StopLossOnFillOrder = StopLossDetails(price=sl) order_sell = MarketOrderRequest( instrument=pair, units=-10, takeProfitOnFill=takeProfitOnFillOrder.data, stopLossOnFill=StopLossOnFillOrder.data) r = orders.OrderCreate(accountID, data=order_sell.data) print("Processing selling order of : {}".format(r)) print("====================") print(r.data) try: response = api.request(r) except V20Error as e: print("V20Error:{}".format(e)) else: print("Respose: {}\n{}".format(r.status_code, json.dumps(response, indent=2)))
def market_order(instrument, type, units, stopLoss, takeProfit): """ Places a market order at that time. returns order ID if successful """ if type == "buy": pass elif type == "sell": units *= -1 else: print("Choose only 'buy' or 'sell'... please and thanks") return 0 inParams = { "order": { "stopLossOnFill": { "timeInForce": "GTC", "price": str(stopLoss) }, "takeProfitOnFill": { "timeInForce": "GTC", "price": str(takeProfit) }, "timeInForce": "FOK", "instrument": instrument, "units": units, "type": "MARKET", "positionFill": "DEFAULT" } } order_post = orders.OrderCreate(accountID=accID, data=inParams) client.request(order_post) print("Market Order placed on " + instrument + "---Units: " + str(units)) return int(order_post.response['orderCreateTransaction']['id'])
def open_limit_order(units, buy_or_sell, price, stop_loss, take_profit, instrument): if buy_or_sell == "SELL": units = -units order_data = { "order": { "price": str(price), "timeInForce": "GTC", "instrument": str(instrument), "units": str(units), "clientExtensions": { "comment": "Algo rulez bitch!" }, "stopLossOnFill": { "timeInForce": "GTC", "price": str(stop_loss) }, "takeProfitOnFill": { "price": str(take_profit) }, "type": "MARKET_IF_TOUCHED", "positionFill": "DEFAULT" } } r = orders.OrderCreate(accountID=accountID, data=order_data) api.request(r) print(r.response, "\n VYTVORENA POZICIA") history_file.write(price)
def order(self, units): mop = {"instrument": self.pt.instrument, "units": units} def frmt(v): # format a number over 6 digits: 12004.1, 1.05455 l = len(str(v).split(".")[0]) return "{{:{}.{}f}}".format(l, 6 - l).format(v) direction = 1 if units > 0 else -1 if self.clargs.takeProfit: # takeProfit specified? add it tpPrice = self.pt._c[self.pt.idx-1] * \ (1.0 + (self.clargs.takeProfit/100.0) * direction) mop.update({ "takeProfitOnFill": TakeProfitDetails(price=frmt(tpPrice)).data }) if self.clargs.stopLoss: # stopLosss specified? add it slPrice = self.pt._c[self.pt.idx-1] * \ (1.0 + (self.clargs.stopLoss/100.0) * -direction) mop.update( {"stopLossOnFill": StopLossDetails(price=frmt(slPrice)).data}) data = MarketOrderRequest(**mop).data r = orders.OrderCreate(accountID=self.accountID, data=data) try: response = self.client.request(r) except V20Error as e: logger.error("V20Error: %s", e) else: logger.info("Response: %d %s", r.status_code, json.dumps(response, indent=2))
def send_stop_loss(self, order: Order) -> Trade: if order.side == constants.BUY: units = order.units elif order.side == constants.SELL: units = -order.units order_data = { 'order': { 'type': order.order_type, 'instrument': order.product_code, 'units': units, 'price': order.price } } req = orders.OrderCreate(accountID=self.account_id, data=order_data) try: resp = self.client.request(req) logger.info(f'action=send_order resp={resp}') except V20Error as e: logger.error(f'action=send_order error={e}') raise ValueError order_id = resp['orderCreateTransaction']['id'] price = order.price units = order.units side = order.side trade = Trade(trade_id=order_id, side=side, price=price, units=units) return trade