Last active
April 12, 2019 01:16
-
-
Save libasoles/5b638b0d1a7cab08c90058f51b51fe64 to your computer and use it in GitHub Desktop.
Trigger de stopLoss y takeProfit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/****************************************************** | |
* | |
* Crea (alertas de) stopLoss y takeProfit. | |
* | |
* Este código es un ejercicio. No me responsabilizo de que | |
* no funcione. Sos el único responsable si lo usas y pones | |
* tu dinero en juego. | |
* | |
* Este script solo funciona en la consola del navegador | |
* en cryptomkt.com | |
* | |
*******************************************************/ | |
cryptoapi = (()=>{ | |
function init() { | |
createLimitsViewer(); | |
} | |
function update() { | |
updateView(); | |
for(const coin of config.coins) { | |
helpers.checkLimits(coin); | |
} | |
} | |
function createLimitsViewer() { | |
// haciendo uso de la variable global base_name, muestro el stop loss | |
$(`<li> | |
<div id="header-limits" class="content-text text-center" style="margin-top: 10px;"> | |
<div style="top: 0px;" class="header_price_container"> | |
<div class="price_container container_bid animation"> | |
<div class="margin-top-neg-4">stop loss</div> | |
<div class="margin-top-neg"><b id="stop-loss-viewer">-</b></div> | |
</div> | |
<div class="price_container margin-left-10 container_ask animation"> | |
<div class="margin-top-neg-4">take profit</div> | |
<div class="margin-top-neg"><b id="take-profit-viewer">-</b></div> | |
</div> | |
</div> | |
</div> | |
</li> | |
`).insertBefore('#alerts_dropdown'); | |
$('<li><span class="divider_nav"> </span></li>').insertBefore('#alerts_dropdown'); | |
} | |
function updateView() { | |
// actualizar valores limit | |
const {stopLoss, takeProfit} = config.limits[base_name] || {}; | |
$('#stop-loss-viewer').text( stopLoss ? '$'+stopLoss : '-'); | |
$('#take-profit-viewer').text( takeProfit ? '$'+takeProfit : '-'); | |
} | |
/** config */ | |
const config = { | |
base: 'ARS', | |
coins: ['ETH', 'XLM'], | |
interval: 2, // segundos | |
limits: {}, | |
} | |
/** helpers */ | |
const helpers = { | |
getTicker: (coin = 'ETH') => { | |
const ticker = window.board[coin+config.base] | |
return { | |
bid: parseFloat(ticker.BID), | |
ask: parseFloat(ticker.ASK), | |
spread: parseFloat((ticker.ASK - ticker.BID).toFixed(2)) | |
} | |
}, | |
getBalance: (currency = 'ARS') => { | |
return window.balances.find(x=>x.currency_name === currency) | |
}, | |
getAvailableBalance: (currency = 'ARS') => { | |
return parseFloat(helpers.getBalance(currency).disponible).toFixed(2); | |
}, | |
createOrder(pair_name, order_type, price, amount) { | |
ajax_start() | |
$.post("/platform/market/" + pair_name + "/open_order", { | |
csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(), | |
order_type: order_type, | |
price: price, | |
amount: amount | |
}).done(function(e) { | |
if ("success" == e.status) { | |
toastr.success(trans.order_ha_sido_abierta, trans.order_abierta); | |
get_market_data(); | |
try { | |
"buy" == order_type ? dataLayer.push({ | |
event: "ordenCompra" | |
}) : dataLayer.push({ | |
event: "ordenVenta" | |
}) | |
} catch (t) {} | |
} else toastr.error(e.message, trans.ha_ocurrido_error) | |
}).fail(function() { | |
toastr.error(trans.lo_lamentamos, trans.ha_ocurrido_error) | |
}).always(function() { | |
ajax_stop() | |
}) | |
}, | |
/** | |
* type: stopLoss|takeProfit | |
*/ | |
setLimit(type, coin, price) { | |
if(typeof config.limits[coin] === 'undefined') { | |
config.limits[coin] = {} | |
} | |
config.limits[coin][type] = price | |
}, | |
getLimits() { | |
return config.limits | |
}, | |
setStopLoss(coin, price) { | |
helpers.setLimit('stopLoss', coin, price) | |
}, | |
setTakeProfit(coin, price) { | |
helpers.setLimit('takeProfit', coin, price) | |
}, | |
checkLimits(coin) { | |
// skip si no hay limites definidos para la moneda | |
if(typeof config.limits[coin] === 'undefined') { | |
return false | |
} | |
const {stopLoss, takeProfit} = config.limits[coin]; | |
const ticker = helpers.getTicker(coin); | |
// skip si el tick no toca los limites establecidos | |
if( (!stopLoss || parseFloat(ticker.ask) > parseFloat(stopLoss)) | |
&& (!takeProfit || parseFloat(ticker.bid) < parseFloat(takeProfit)) ) { | |
return false | |
} | |
// skip si no hay balance de esa moneda | |
const available = helpers.getAvailableBalance(coin) | |
if(available < window.min_sell ) { | |
return false | |
} | |
const pair_name = coin + config.base; | |
let price; | |
// vender | |
if(parseFloat(ticker.ask) <= parseFloat(stopLoss)) { | |
price = ticker.ask | |
} else if(parseFloat(ticker.bid) >= parseFloat(takeProfit)){ | |
price = ticker.bid | |
} | |
console.log('CREA TU ORDEN!', pair_name, 'sell', price, available); | |
toastr.success(`Vende ${available} ${coin} a ${price}`, 'CREA TU ORDEN!'); // mensaje en pantalla | |
// helpers.createOrder(pair_name, 'sell', price, available) // descomentar para darle funcionalidad | |
} | |
} | |
init() | |
update() | |
setInterval(update, config.interval * 1000) | |
/** | |
* API | |
*/ | |
return { | |
getAvailableBalance: helpers.getAvailableBalance, | |
getTicker: helpers.getTicker, | |
createOrder: helpers.createOrder, | |
setStopLoss: helpers.setStopLoss, | |
setTakeProfit: helpers.setTakeProfit, | |
getLimits: helpers.getLimits, | |
}; | |
})(); | |
// Ejemplo: | |
// cryptoapi.setStopLoss('XLM', 9.56); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Muy interesante estimado... Felicitaciones